file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
indexTree.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/tree'; import { Iterable } from 'vs/base/common/iterator'; import { AbstractTree, IAbstractTreeOptions } from 'vs/base/browser/ui/tree/abstractTree'; import { IndexTreeModel, IList } from 'vs/base/browser/ui/tree/indexTreeModel'; import { ITreeElement, ITreeModel, ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; export interface IIndexTreeOptions<T, TFilterData = void> extends IAbstractTreeOptions<T, TFilterData> { } export class IndexTree<T, TFilterData = void> extends AbstractTree<T, TFilterData, number[]> { protected override model!: IndexTreeModel<T, TFilterData>; constructor( user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: ITreeRenderer<T, TFilterData, any>[], private rootElement: T, options: IIndexTreeOptions<T, TFilterData> = {} ) { super(user, container, delegate, renderers, options); } splice(location: number[], deleteCount: number, toInsert: Iterable<ITreeElement<T>> = Iterable.empty()): void { this.model.splice(location, deleteCount, toInsert); }
(location?: number[]): void { if (location === undefined) { this.view.rerender(); return; } this.model.rerender(location); } updateElementHeight(location: number[], height: number): void { this.model.updateElementHeight(location, height); } protected createModel(user: string, view: IList<ITreeNode<T, TFilterData>>, options: IIndexTreeOptions<T, TFilterData>): ITreeModel<T, TFilterData, number[]> { return new IndexTreeModel(user, view, this.rootElement, options); } }
rerender
identifier_name
indexTree.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/tree'; import { Iterable } from 'vs/base/common/iterator'; import { AbstractTree, IAbstractTreeOptions } from 'vs/base/browser/ui/tree/abstractTree'; import { IndexTreeModel, IList } from 'vs/base/browser/ui/tree/indexTreeModel'; import { ITreeElement, ITreeModel, ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; export interface IIndexTreeOptions<T, TFilterData = void> extends IAbstractTreeOptions<T, TFilterData> { } export class IndexTree<T, TFilterData = void> extends AbstractTree<T, TFilterData, number[]> { protected override model!: IndexTreeModel<T, TFilterData>; constructor( user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: ITreeRenderer<T, TFilterData, any>[], private rootElement: T, options: IIndexTreeOptions<T, TFilterData> = {} ) { super(user, container, delegate, renderers, options); } splice(location: number[], deleteCount: number, toInsert: Iterable<ITreeElement<T>> = Iterable.empty()): void { this.model.splice(location, deleteCount, toInsert); } rerender(location?: number[]): void
updateElementHeight(location: number[], height: number): void { this.model.updateElementHeight(location, height); } protected createModel(user: string, view: IList<ITreeNode<T, TFilterData>>, options: IIndexTreeOptions<T, TFilterData>): ITreeModel<T, TFilterData, number[]> { return new IndexTreeModel(user, view, this.rootElement, options); } }
{ if (location === undefined) { this.view.rerender(); return; } this.model.rerender(location); }
identifier_body
indexTree.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import 'vs/css!./media/tree'; import { Iterable } from 'vs/base/common/iterator'; import { AbstractTree, IAbstractTreeOptions } from 'vs/base/browser/ui/tree/abstractTree'; import { IndexTreeModel, IList } from 'vs/base/browser/ui/tree/indexTreeModel'; import { ITreeElement, ITreeModel, ITreeNode, ITreeRenderer } from 'vs/base/browser/ui/tree/tree'; import { IListVirtualDelegate } from 'vs/base/browser/ui/list/list'; export interface IIndexTreeOptions<T, TFilterData = void> extends IAbstractTreeOptions<T, TFilterData> { } export class IndexTree<T, TFilterData = void> extends AbstractTree<T, TFilterData, number[]> { protected override model!: IndexTreeModel<T, TFilterData>; constructor( user: string, container: HTMLElement, delegate: IListVirtualDelegate<T>, renderers: ITreeRenderer<T, TFilterData, any>[], private rootElement: T, options: IIndexTreeOptions<T, TFilterData> = {} ) { super(user, container, delegate, renderers, options); } splice(location: number[], deleteCount: number, toInsert: Iterable<ITreeElement<T>> = Iterable.empty()): void { this.model.splice(location, deleteCount, toInsert); } rerender(location?: number[]): void { if (location === undefined) { this.view.rerender(); return; } this.model.rerender(location); } updateElementHeight(location: number[], height: number): void {
} protected createModel(user: string, view: IList<ITreeNode<T, TFilterData>>, options: IIndexTreeOptions<T, TFilterData>): ITreeModel<T, TFilterData, number[]> { return new IndexTreeModel(user, view, this.rootElement, options); } }
this.model.updateElementHeight(location, height);
random_line_split
summary.rs
use std::collections::HashMap; use std::mem; use std::rc::Rc; use semver::Version; use core::{Dependency, PackageId, SourceId}; use util::CargoResult; /// Subset of a `Manifest`. Contains only the most important informations about /// a package. /// /// Summaries are cloned, and should not be mutated after creation #[derive(Debug, Clone)] pub struct Summary { inner: Rc<Inner>, } #[derive(Debug, Clone)] struct Inner { package_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>, checksum: Option<String>, } impl Summary { pub fn new(pkg_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>) -> CargoResult<Summary> { for dep in dependencies.iter() { if features.get(dep.name()).is_some() { bail!("Features and dependencies cannot have the \ same name: `{}`", dep.name()) } if dep.is_optional() && !dep.is_transitive() { bail!("Dev-dependencies are not allowed to be optional: `{}`", dep.name()) } } for (feature, list) in features.iter() { for dep in list.iter() { let mut parts = dep.splitn(2, '/'); let dep = parts.next().unwrap(); let is_reexport = parts.next().is_some(); if !is_reexport && features.get(dep).is_some() { continue } match dependencies.iter().find(|d| d.name() == dep) { Some(d) => { if d.is_optional() || is_reexport { continue } bail!("Feature `{}` depends on `{}` which is not an \ optional dependency.\nConsider adding \ `optional = true` to the dependency", feature, dep) } None if is_reexport => { bail!("Feature `{}` requires `{}` which is not an \ optional dependency", feature, dep) } None => { bail!("Feature `{}` includes `{}` which is neither \ a dependency nor another feature", feature, dep) } } } } Ok(Summary { inner: Rc::new(Inner { package_id: pkg_id, dependencies: dependencies, features: features, checksum: None, }), }) } pub fn package_id(&self) -> &PackageId { &self.inner.package_id } pub fn
(&self) -> &str { self.package_id().name() } pub fn version(&self) -> &Version { self.package_id().version() } pub fn source_id(&self) -> &SourceId { self.package_id().source_id() } pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies } pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features } pub fn checksum(&self) -> Option<&str> { self.inner.checksum.as_ref().map(|s| &s[..]) } pub fn override_id(mut self, id: PackageId) -> Summary { Rc::make_mut(&mut self.inner).package_id = id; self } pub fn set_checksum(mut self, cksum: String) -> Summary { Rc::make_mut(&mut self.inner).checksum = Some(cksum); self } pub fn map_dependencies<F>(mut self, f: F) -> Summary where F: FnMut(Dependency) -> Dependency { { let slot = &mut Rc::make_mut(&mut self.inner).dependencies; let deps = mem::replace(slot, Vec::new()); *slot = deps.into_iter().map(f).collect(); } self } pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId) -> Summary { let me = if self.package_id().source_id() == to_replace { let new_id = self.package_id().with_source_id(replace_with); self.override_id(new_id) } else { self }; me.map_dependencies(|dep| { dep.map_source(to_replace, replace_with) }) } } impl PartialEq for Summary { fn eq(&self, other: &Summary) -> bool { self.inner.package_id == other.inner.package_id } }
name
identifier_name
summary.rs
use std::collections::HashMap; use std::mem; use std::rc::Rc; use semver::Version; use core::{Dependency, PackageId, SourceId}; use util::CargoResult; /// Subset of a `Manifest`. Contains only the most important informations about /// a package. /// /// Summaries are cloned, and should not be mutated after creation #[derive(Debug, Clone)] pub struct Summary { inner: Rc<Inner>, } #[derive(Debug, Clone)] struct Inner { package_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>, checksum: Option<String>, } impl Summary { pub fn new(pkg_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>) -> CargoResult<Summary> { for dep in dependencies.iter() { if features.get(dep.name()).is_some() { bail!("Features and dependencies cannot have the \ same name: `{}`", dep.name()) } if dep.is_optional() && !dep.is_transitive() { bail!("Dev-dependencies are not allowed to be optional: `{}`", dep.name()) } } for (feature, list) in features.iter() { for dep in list.iter() { let mut parts = dep.splitn(2, '/'); let dep = parts.next().unwrap(); let is_reexport = parts.next().is_some(); if !is_reexport && features.get(dep).is_some() { continue } match dependencies.iter().find(|d| d.name() == dep) { Some(d) => { if d.is_optional() || is_reexport { continue } bail!("Feature `{}` depends on `{}` which is not an \ optional dependency.\nConsider adding \ `optional = true` to the dependency", feature, dep) } None if is_reexport => { bail!("Feature `{}` requires `{}` which is not an \ optional dependency", feature, dep) } None => { bail!("Feature `{}` includes `{}` which is neither \ a dependency nor another feature", feature, dep) } } } } Ok(Summary { inner: Rc::new(Inner { package_id: pkg_id, dependencies: dependencies, features: features, checksum: None, }), }) } pub fn package_id(&self) -> &PackageId { &self.inner.package_id } pub fn name(&self) -> &str { self.package_id().name() } pub fn version(&self) -> &Version { self.package_id().version() } pub fn source_id(&self) -> &SourceId { self.package_id().source_id() } pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies } pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features } pub fn checksum(&self) -> Option<&str> { self.inner.checksum.as_ref().map(|s| &s[..]) } pub fn override_id(mut self, id: PackageId) -> Summary { Rc::make_mut(&mut self.inner).package_id = id; self } pub fn set_checksum(mut self, cksum: String) -> Summary { Rc::make_mut(&mut self.inner).checksum = Some(cksum); self } pub fn map_dependencies<F>(mut self, f: F) -> Summary where F: FnMut(Dependency) -> Dependency { { let slot = &mut Rc::make_mut(&mut self.inner).dependencies; let deps = mem::replace(slot, Vec::new()); *slot = deps.into_iter().map(f).collect(); } self } pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId) -> Summary
} impl PartialEq for Summary { fn eq(&self, other: &Summary) -> bool { self.inner.package_id == other.inner.package_id } }
{ let me = if self.package_id().source_id() == to_replace { let new_id = self.package_id().with_source_id(replace_with); self.override_id(new_id) } else { self }; me.map_dependencies(|dep| { dep.map_source(to_replace, replace_with) }) }
identifier_body
summary.rs
use std::collections::HashMap; use std::mem; use std::rc::Rc; use semver::Version; use core::{Dependency, PackageId, SourceId}; use util::CargoResult; /// Subset of a `Manifest`. Contains only the most important informations about /// a package. /// /// Summaries are cloned, and should not be mutated after creation #[derive(Debug, Clone)] pub struct Summary { inner: Rc<Inner>, } #[derive(Debug, Clone)] struct Inner { package_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>, checksum: Option<String>, } impl Summary { pub fn new(pkg_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>) -> CargoResult<Summary> { for dep in dependencies.iter() { if features.get(dep.name()).is_some() { bail!("Features and dependencies cannot have the \ same name: `{}`", dep.name()) } if dep.is_optional() && !dep.is_transitive() { bail!("Dev-dependencies are not allowed to be optional: `{}`", dep.name()) } } for (feature, list) in features.iter() { for dep in list.iter() { let mut parts = dep.splitn(2, '/'); let dep = parts.next().unwrap(); let is_reexport = parts.next().is_some(); if !is_reexport && features.get(dep).is_some() { continue } match dependencies.iter().find(|d| d.name() == dep) { Some(d) => { if d.is_optional() || is_reexport { continue } bail!("Feature `{}` depends on `{}` which is not an \ optional dependency.\nConsider adding \ `optional = true` to the dependency", feature, dep) } None if is_reexport => { bail!("Feature `{}` requires `{}` which is not an \ optional dependency", feature, dep) } None => { bail!("Feature `{}` includes `{}` which is neither \ a dependency nor another feature", feature, dep) } } } } Ok(Summary { inner: Rc::new(Inner { package_id: pkg_id, dependencies: dependencies, features: features, checksum: None, }), }) } pub fn package_id(&self) -> &PackageId { &self.inner.package_id } pub fn name(&self) -> &str { self.package_id().name() } pub fn version(&self) -> &Version { self.package_id().version() } pub fn source_id(&self) -> &SourceId { self.package_id().source_id() } pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies } pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features } pub fn checksum(&self) -> Option<&str> { self.inner.checksum.as_ref().map(|s| &s[..]) } pub fn override_id(mut self, id: PackageId) -> Summary { Rc::make_mut(&mut self.inner).package_id = id; self } pub fn set_checksum(mut self, cksum: String) -> Summary { Rc::make_mut(&mut self.inner).checksum = Some(cksum); self } pub fn map_dependencies<F>(mut self, f: F) -> Summary where F: FnMut(Dependency) -> Dependency { { let slot = &mut Rc::make_mut(&mut self.inner).dependencies; let deps = mem::replace(slot, Vec::new()); *slot = deps.into_iter().map(f).collect(); } self } pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId) -> Summary { let me = if self.package_id().source_id() == to_replace { let new_id = self.package_id().with_source_id(replace_with); self.override_id(new_id) } else { self }; me.map_dependencies(|dep| {
} } impl PartialEq for Summary { fn eq(&self, other: &Summary) -> bool { self.inner.package_id == other.inner.package_id } }
dep.map_source(to_replace, replace_with) })
random_line_split
summary.rs
use std::collections::HashMap; use std::mem; use std::rc::Rc; use semver::Version; use core::{Dependency, PackageId, SourceId}; use util::CargoResult; /// Subset of a `Manifest`. Contains only the most important informations about /// a package. /// /// Summaries are cloned, and should not be mutated after creation #[derive(Debug, Clone)] pub struct Summary { inner: Rc<Inner>, } #[derive(Debug, Clone)] struct Inner { package_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>, checksum: Option<String>, } impl Summary { pub fn new(pkg_id: PackageId, dependencies: Vec<Dependency>, features: HashMap<String, Vec<String>>) -> CargoResult<Summary> { for dep in dependencies.iter() { if features.get(dep.name()).is_some() { bail!("Features and dependencies cannot have the \ same name: `{}`", dep.name()) } if dep.is_optional() && !dep.is_transitive() { bail!("Dev-dependencies are not allowed to be optional: `{}`", dep.name()) } } for (feature, list) in features.iter() { for dep in list.iter() { let mut parts = dep.splitn(2, '/'); let dep = parts.next().unwrap(); let is_reexport = parts.next().is_some(); if !is_reexport && features.get(dep).is_some() { continue } match dependencies.iter().find(|d| d.name() == dep) { Some(d) =>
None if is_reexport => { bail!("Feature `{}` requires `{}` which is not an \ optional dependency", feature, dep) } None => { bail!("Feature `{}` includes `{}` which is neither \ a dependency nor another feature", feature, dep) } } } } Ok(Summary { inner: Rc::new(Inner { package_id: pkg_id, dependencies: dependencies, features: features, checksum: None, }), }) } pub fn package_id(&self) -> &PackageId { &self.inner.package_id } pub fn name(&self) -> &str { self.package_id().name() } pub fn version(&self) -> &Version { self.package_id().version() } pub fn source_id(&self) -> &SourceId { self.package_id().source_id() } pub fn dependencies(&self) -> &[Dependency] { &self.inner.dependencies } pub fn features(&self) -> &HashMap<String, Vec<String>> { &self.inner.features } pub fn checksum(&self) -> Option<&str> { self.inner.checksum.as_ref().map(|s| &s[..]) } pub fn override_id(mut self, id: PackageId) -> Summary { Rc::make_mut(&mut self.inner).package_id = id; self } pub fn set_checksum(mut self, cksum: String) -> Summary { Rc::make_mut(&mut self.inner).checksum = Some(cksum); self } pub fn map_dependencies<F>(mut self, f: F) -> Summary where F: FnMut(Dependency) -> Dependency { { let slot = &mut Rc::make_mut(&mut self.inner).dependencies; let deps = mem::replace(slot, Vec::new()); *slot = deps.into_iter().map(f).collect(); } self } pub fn map_source(self, to_replace: &SourceId, replace_with: &SourceId) -> Summary { let me = if self.package_id().source_id() == to_replace { let new_id = self.package_id().with_source_id(replace_with); self.override_id(new_id) } else { self }; me.map_dependencies(|dep| { dep.map_source(to_replace, replace_with) }) } } impl PartialEq for Summary { fn eq(&self, other: &Summary) -> bool { self.inner.package_id == other.inner.package_id } }
{ if d.is_optional() || is_reexport { continue } bail!("Feature `{}` depends on `{}` which is not an \ optional dependency.\nConsider adding \ `optional = true` to the dependency", feature, dep) }
conditional_block
urls.py
"""myproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [ url(r'^admin/', admin.site.urls), ] if settings.DEBUG:
import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
conditional_block
urls.py
"""myproject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url, include from django.contrib import admin from django.conf import settings urlpatterns = [
if settings.DEBUG: import debug_toolbar urlpatterns += [ url(r'^__debug__/', include(debug_toolbar.urls)), ]
url(r'^admin/', admin.site.urls), ]
random_line_split
products.module.ts
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import { NgModule } from '@angular/core'; import { ProductsRoutingModule } from './products-routing.module'; import { ProductComponent } from './components/product.component'; import { SharedModule } from '../shared/shared.module'; import { ProductsFacade } from './products.facade'; @NgModule({ declarations: [ ProductComponent ], imports: [ SharedModule, ProductsRoutingModule ], providers: [ ProductsFacade ] }) export class
{ }
ProductsModule
identifier_name
products.module.ts
/* Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import { ProductsRoutingModule } from './products-routing.module'; import { ProductComponent } from './components/product.component'; import { SharedModule } from '../shared/shared.module'; import { ProductsFacade } from './products.facade'; @NgModule({ declarations: [ ProductComponent ], imports: [ SharedModule, ProductsRoutingModule ], providers: [ ProductsFacade ] }) export class ProductsModule { }
See the License for the specific language governing permissions and limitations under the License. */ import { NgModule } from '@angular/core';
random_line_split
index.d.ts
import * as React from "react"; declare module "react-css-themr" { type TReactCSSThemrTheme = { [key: string]: string | TReactCSSThemrTheme } type TMapThemrProps<P> = (ownProps: P, theme: TReactCSSThemrTheme) => P & { theme: TReactCSSThemrTheme } export function themeable(...themes: Array<TReactCSSThemrTheme>): TReactCSSThemrTheme; export interface IThemrOptions { /** @default "deeply" */ composeTheme?: "deeply" | "softly" | false, //currently there's no way to lift decorated component's generic type argument (P) to upper decorator //that's why just {} mapThemrProps?: TMapThemrProps<{}> } export interface ThemeProviderProps { innerRef?: Function, theme: TReactCSSThemrTheme } export class
extends React.Component<ThemeProviderProps, any> { } interface ThemedComponent<P, S> extends React.Component<P, S> { } interface ThemedComponentClass<P, S> extends React.ComponentClass<P> { new(props?: P, context?: any): ThemedComponent<P, S>; } export function themr( identifier: string | number | symbol, defaultTheme?: {}, options?: IThemrOptions ): <P, S>(component: (new(props?: P, context?: any) => React.Component<P, S>) | React.SFC<P>) => ThemedComponentClass<P & { mapThemrProps?: TMapThemrProps<P> }, S>; }
ThemeProvider
identifier_name
index.d.ts
import * as React from "react"; declare module "react-css-themr" { type TReactCSSThemrTheme = { [key: string]: string | TReactCSSThemrTheme } type TMapThemrProps<P> = (ownProps: P, theme: TReactCSSThemrTheme) => P & { theme: TReactCSSThemrTheme } export function themeable(...themes: Array<TReactCSSThemrTheme>): TReactCSSThemrTheme; export interface IThemrOptions { /** @default "deeply" */ composeTheme?: "deeply" | "softly" | false, //currently there's no way to lift decorated component's generic type argument (P) to upper decorator //that's why just {} mapThemrProps?: TMapThemrProps<{}> } export interface ThemeProviderProps { innerRef?: Function, theme: TReactCSSThemrTheme } export class ThemeProvider extends React.Component<ThemeProviderProps, any> { } interface ThemedComponent<P, S> extends React.Component<P, S> { } interface ThemedComponentClass<P, S> extends React.ComponentClass<P> { new(props?: P, context?: any): ThemedComponent<P, S>; } export function themr( identifier: string | number | symbol, defaultTheme?: {}, options?: IThemrOptions
): <P, S>(component: (new(props?: P, context?: any) => React.Component<P, S>) | React.SFC<P>) => ThemedComponentClass<P & { mapThemrProps?: TMapThemrProps<P> }, S>; }
random_line_split
logging.py
"""Access and control log capturing.""" import logging import os import re import sys from contextlib import contextmanager from io import StringIO from pathlib import Path from typing import AbstractSet from typing import Dict from typing import Generator from typing import List from typing import Mapping from typing import Optional from typing import Tuple from typing import TypeVar from typing import Union from _pytest import nodes from _pytest._io import TerminalWriter from _pytest.capture import CaptureManager from _pytest.compat import final from _pytest.compat import nullcontext from _pytest.config import _strtobool from _pytest.config import Config from _pytest.config import create_terminal_writer from _pytest.config import hookimpl from _pytest.config import UsageError from _pytest.config.argparsing import Parser from _pytest.deprecated import check_ispytest from _pytest.fixtures import fixture from _pytest.fixtures import FixtureRequest from _pytest.main import Session from _pytest.store import StoreKey from _pytest.terminal import TerminalReporter DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S" _ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m") caplog_handler_key = StoreKey["LogCaptureHandler"]() caplog_records_key = StoreKey[Dict[str, List[logging.LogRecord]]]() def _remove_ansi_escape_sequences(text: str) -> str: return _ANSI_ESCAPE_SEQ.sub("", text) class ColoredLevelFormatter(logging.Formatter): """A logging formatter which colorizes the %(levelname)..s part of the log format passed to __init__.""" LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = { logging.CRITICAL: {"red"}, logging.ERROR: {"red", "bold"}, logging.WARNING: {"yellow"}, logging.WARN: {"yellow"}, logging.INFO: {"green"}, logging.DEBUG: {"purple"}, logging.NOTSET: set(), } LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)") def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._original_fmt = self._style._fmt self._level_to_fmt_mapping: Dict[int, str] = {} assert self._fmt is not None levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt) if not levelname_fmt_match: return levelname_fmt = levelname_fmt_match.group() for level, color_opts in self.LOGLEVEL_COLOROPTS.items(): formatted_levelname = levelname_fmt % { "levelname": logging.getLevelName(level) } # add ANSI escape sequences around the formatted levelname color_kwargs = {name: True for name in color_opts} colorized_formatted_levelname = terminalwriter.markup( formatted_levelname, **color_kwargs ) self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub( colorized_formatted_levelname, self._fmt ) def format(self, record: logging.LogRecord) -> str: fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) self._style._fmt = fmt return super().format(record) class PercentStyleMultiline(logging.PercentStyle): """A logging style with special support for multiline messages. If the message of a record consists of multiple lines, this style formats the message as if each line were logged separately. """ def __init__(self, fmt: str, auto_indent: Union[int, str, bool, None]) -> None: super().__init__(fmt) self._auto_indent = self._get_auto_indent(auto_indent) @staticmethod def _update_message( record_dict: Dict[str, object], message: str ) -> Dict[str, object]: tmp = record_dict.copy() tmp["message"] = message return tmp @staticmethod def _get_auto_indent(auto_indent_option: Union[int, str, bool, None]) -> int: """Determine the current auto indentation setting. Specify auto indent behavior (on/off/fixed) by passing in extra={"auto_indent": [value]} to the call to logging.log() or using a --log-auto-indent [value] command line or the log_auto_indent [value] config option. Default behavior is auto-indent off. Using the string "True" or "on" or the boolean True as the value turns auto indent on, using the string "False" or "off" or the boolean False or the int 0 turns it off, and specifying a positive integer fixes the indentation position to the value specified. Any other values for the option are invalid, and will silently be converted to the default. :param None|bool|int|str auto_indent_option: User specified option for indentation from command line, config or extra kwarg. Accepts int, bool or str. str option accepts the same range of values as boolean config options, as well as positive integers represented in str form. :returns: Indentation value, which can be -1 (automatically determine indentation) or 0 (auto-indent turned off) or >0 (explicitly set indentation position). """ if auto_indent_option is None: return 0 elif isinstance(auto_indent_option, bool): if auto_indent_option: return -1 else: return 0 elif isinstance(auto_indent_option, int): return int(auto_indent_option) elif isinstance(auto_indent_option, str): try: return int(auto_indent_option) except ValueError: pass try: if _strtobool(auto_indent_option): return -1 except ValueError: return 0 return 0 def format(self, record: logging.LogRecord) -> str: if "\n" in record.message: if hasattr(record, "auto_indent"): # Passed in from the "extra={}" kwarg on the call to logging.log(). auto_indent = self._get_auto_indent(record.auto_indent) # type: ignore[attr-defined] else: auto_indent = self._auto_indent if auto_indent: lines = record.message.splitlines() formatted = self._fmt % self._update_message(record.__dict__, lines[0]) if auto_indent < 0: indentation = _remove_ansi_escape_sequences(formatted).find( lines[0] ) else: # Optimizes logging by allowing a fixed indentation. indentation = auto_indent lines[0] = formatted return ("\n" + " " * indentation).join(lines) return self._fmt % record.__dict__ def get_option_ini(config: Config, *names: str): for name in names: ret = config.getoption(name) # 'default' arg won't work as expected if ret is None: ret = config.getini(name) if ret: return ret def pytest_addoption(parser: Parser) -> None: """Add options to control log capturing.""" group = parser.getgroup("logging") def add_option_ini(option, dest, default=None, type=None, **kwargs): parser.addini( dest, default=default, type=type, help="default value for " + option ) group.addoption(option, dest=dest, **kwargs) add_option_ini( "--log-level", dest="log_level", default=None, metavar="LEVEL", help=( "level of messages to catch/display.\n" "Not set by default, so it depends on the root/parent log handler's" ' effective level, where it is "WARNING" by default.' ), ) add_option_ini( "--log-format", dest="log_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-date-format", dest="log_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) parser.addini( "log_cli", default=False, type="bool", help='enable log display during test run (also known as "live logging").', ) add_option_ini( "--log-cli-level", dest="log_cli_level", default=None, help="cli logging level." ) add_option_ini( "--log-cli-format", dest="log_cli_format", default=None, help="log format as used by the logging module.", ) add_option_ini( "--log-cli-date-format", dest="log_cli_date_format", default=None, help="log date format as used by the logging module.", ) add_option_ini( "--log-file", dest="log_file", default=None, help="path to a file when logging will be written to.", ) add_option_ini( "--log-file-level", dest="log_file_level", default=None, help="log file logging level.", ) add_option_ini( "--log-file-format", dest="log_file_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-file-date-format", dest="log_file_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) add_option_ini( "--log-auto-indent", dest="log_auto_indent", default=None, help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.", ) _HandlerType = TypeVar("_HandlerType", bound=logging.Handler) # Not using @contextmanager for performance reasons. class catching_logs: """Context manager that prepares the whole logging machinery properly.""" __slots__ = ("handler", "level", "orig_level") def __init__(self, handler: _HandlerType, level: Optional[int] = None) -> None: self.handler = handler self.level = level def __enter__(self): root_logger = logging.getLogger() if self.level is not None: self.handler.setLevel(self.level) root_logger.addHandler(self.handler) if self.level is not None: self.orig_level = root_logger.level root_logger.setLevel(min(self.orig_level, self.level)) return self.handler def __exit__(self, type, value, traceback): root_logger = logging.getLogger() if self.level is not None: root_logger.setLevel(self.orig_level) root_logger.removeHandler(self.handler) class LogCaptureHandler(logging.StreamHandler): """A logging handler that stores log records and the log text.""" stream: StringIO def __init__(self) -> None: """Create a new log handler.""" super().__init__(StringIO()) self.records: List[logging.LogRecord] = [] def emit(self, record: logging.LogRecord) -> None: """Keep the log records in a list in addition to the log text.""" self.records.append(record) super().emit(record) def reset(self) -> None: self.records = [] self.stream = StringIO() def handleError(self, record: logging.LogRecord) -> None: if logging.raiseExceptions: # Fail the test if the log message is bad (emit failed). # The default behavior of logging is to print "Logging error" # to stderr with the call stack and some extra details. # pytest wants to make such mistakes visible during testing. raise @final class LogCaptureFixture: """Provides access and control of log capturing.""" def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: check_ispytest(_ispytest) self._item = item self._initial_handler_level: Optional[int] = None # Dict of log name -> log level. self._initial_logger_levels: Dict[Optional[str], int] = {} def _finalize(self) -> None: """Finalize the fixture. This restores the log levels changed by :meth:`set_level`. """ # Restore log levels. if self._initial_handler_level is not None: self.handler.setLevel(self._initial_handler_level) for logger_name, level in self._initial_logger_levels.items(): logger = logging.getLogger(logger_name) logger.setLevel(level) @property def handler(self) -> LogCaptureHandler: """Get the logging handler used by the fixture. :rtype: LogCaptureHandler """ return self._item._store[caplog_handler_key] def get_records(self, when: str) -> List[logging.LogRecord]: """Get the logging records for one of the possible test phases. :param str when: Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown". :returns: The list of captured records at the given stage. :rtype: List[logging.LogRecord] .. versionadded:: 3.4 """ return self._item._store[caplog_records_key].get(when, []) @property def text(self) -> str: """The formatted log text.""" return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) @property def records(self) -> List[logging.LogRecord]: """The list of log records.""" return self.handler.records @property def record_tuples(self) -> List[Tuple[str, int, str]]: """A list of a stripped down version of log records intended for use in assertion comparison. The format of the tuple is: (logger_name, log_level, message) """ return [(r.name, r.levelno, r.getMessage()) for r in self.records] @property def messages(self) -> List[str]: """A list of format-interpolated log messages. Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list are all interpolated. Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with levels, timestamps, etc, making exact comparisons more reliable. Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments to the logging functions) is not included, as this is added by the formatter in the handler. .. versionadded:: 3.7 """ return [r.getMessage() for r in self.records] def clear(self) -> None: """Reset the list of log records and the captured log text.""" self.handler.reset() def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None: """Set the level of a logger for the duration of a test. .. versionchanged:: 3.4 The levels of the loggers changed by this function will be restored to their initial values at the end of the test. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) # Save the original log-level to restore it during teardown. self._initial_logger_levels.setdefault(logger, logger_obj.level) logger_obj.setLevel(level) if self._initial_handler_level is None: self._initial_handler_level = self.handler.level self.handler.setLevel(level) @contextmanager def at_level( self, level: int, logger: Optional[str] = None ) -> Generator[None, None, None]: """Context manager that sets the level for capturing of logs. After the end of the 'with' statement the level is restored to its original value. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) orig_level = logger_obj.level logger_obj.setLevel(level) handler_orig_level = self.handler.level self.handler.setLevel(level) try: yield finally: logger_obj.setLevel(orig_level) self.handler.setLevel(handler_orig_level) @fixture def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture, None, None]: """Access and control log capturing. Captured logs are available through the following properties/methods:: * caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string """ result = LogCaptureFixture(request.node, _ispytest=True) yield result result._finalize() def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]: for setting_name in setting_names: log_level = config.getoption(setting_name) if log_level is None: log_level = config.getini(setting_name) if log_level: break else: return None if isinstance(log_level, str): log_level = log_level.upper() try: return int(getattr(logging, log_level, log_level)) except ValueError as e: # Python logging does not recognise this as a logging level raise UsageError( "'{}' is not recognized as a logging level name for " "'{}'. Please consider passing the " "logging level num instead.".format(log_level, setting_name) ) from e # run after terminalreporter/capturemanager are configured @hookimpl(trylast=True) def pytest_configure(config: Config) -> None: config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") class LoggingPlugin: """Attaches to the logging module and captures log messages for each test.""" def __init__(self, config: Config) -> None: """Create a new plugin to capture log messages. The formatter can be safely shared across all handlers so create a single one for the entire test session here. """ self._config = config # Report logging. self.formatter = self._create_formatter( get_option_ini(config, "log_format"), get_option_ini(config, "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_level = get_log_level_for_setting(config, "log_level") self.caplog_handler = LogCaptureHandler() self.caplog_handler.setFormatter(self.formatter) self.report_handler = LogCaptureHandler() self.report_handler.setFormatter(self.formatter) # File logging. self.log_file_level = get_log_level_for_setting(config, "log_file_level") log_file = get_option_ini(config, "log_file") or os.devnull if log_file != os.devnull: directory = os.path.dirname(os.path.abspath(log_file)) if not os.path.isdir(directory): os.makedirs(directory) self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8") log_file_format = get_option_ini(config, "log_file_format", "log_format") log_file_date_format = get_option_ini( config, "log_file_date_format", "log_date_format" ) log_file_formatter = logging.Formatter( log_file_format, datefmt=log_file_date_format ) self.log_file_handler.setFormatter(log_file_formatter) # CLI/live logging. self.log_cli_level = get_log_level_for_setting( config, "log_cli_level", "log_level" ) if self._log_cli_enabled(): terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") capture_manager = config.pluginmanager.get_plugin("capturemanager") # if capturemanager plugin is disabled, live logging still works. self.log_cli_handler: Union[ _LiveLoggingStreamHandler, _LiveLoggingNullHandler ] = _LiveLoggingStreamHandler(terminal_reporter, capture_manager) else: self.log_cli_handler = _LiveLoggingNullHandler() log_cli_formatter = self._create_formatter( get_option_ini(config, "log_cli_format", "log_format"), get_option_ini(config, "log_cli_date_format", "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_cli_handler.setFormatter(log_cli_formatter) def _create_formatter(self, log_format, log_date_format, auto_indent): # Color option doesn't exist if terminal plugin is disabled. color = getattr(self._config.option, "color", "no") if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search( log_format ): formatter: logging.Formatter = ColoredLevelFormatter( create_terminal_writer(self._config), log_format, log_date_format ) else: formatter = logging.Formatter(log_format, log_date_format) formatter._style = PercentStyleMultiline( formatter._style._fmt, auto_indent=auto_indent ) return formatter def set_log_path(self, fname: str) -> None: """Set the filename parameter for Logging.FileHandler(). Creates parent directory if it does not exist. .. warning:: This is an experimental API. """ fpath = Path(fname) if not fpath.is_absolute(): fpath = self._config.rootpath / fpath if not fpath.parent.exists(): fpath.parent.mkdir(exist_ok=True, parents=True) stream = fpath.open(mode="w", encoding="UTF-8") if sys.version_info >= (3, 7): old_stream = self.log_file_handler.setStream(stream) else: old_stream = self.log_file_handler.stream self.log_file_handler.acquire() try: self.log_file_handler.flush() self.log_file_handler.stream = stream finally: self.log_file_handler.release() if old_stream: old_stream.close() def _log_cli_enabled(self): """Return whether live logging is enabled.""" enabled = self._config.getoption( "--log-cli-level" ) is not None or self._config.getini("log_cli") if not enabled: return False terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter") if terminal_reporter is None: # terminal reporter is disabled e.g. by pytest-xdist. return False return True @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionstart(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionstart") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True, tryfirst=True) def pytest_collection(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("collection") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True) def pytest_runtestloop(self, session: Session) -> Generator[None, None, None]: if session.config.option.collectonly: yield return if self._log_cli_enabled() and self._config.getoption("verbose") < 1: # The verbose flag is needed to avoid messy test progress output. self._config.option.verbose = 1 with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield # Run all the tests. @hookimpl def pytest_runtest_logstart(self) -> None: self.log_cli_handler.reset() self.log_cli_handler.set_when("start") @hookimpl def pytest_runtest_logreport(self) -> None: self.log_cli_handler.set_when("logreport") def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]: """Implement the internals of the pytest_runtest_xxx() hooks.""" with catching_logs( self.caplog_handler, level=self.log_level, ) as caplog_handler, catching_logs( self.report_handler, level=self.log_level, ) as report_handler: caplog_handler.reset() report_handler.reset() item._store[caplog_records_key][when] = caplog_handler.records item._store[caplog_handler_key] = caplog_handler yield log = report_handler.stream.getvalue().strip() item.add_report_section(when, "log", log) @hookimpl(hookwrapper=True) def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("setup") empty: Dict[str, List[logging.LogRecord]] = {} item._store[caplog_records_key] = empty yield from self._runtest_for(item, "setup") @hookimpl(hookwrapper=True) def pytest_runtest_call(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("call") yield from self._runtest_for(item, "call") @hookimpl(hookwrapper=True) def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("teardown") yield from self._runtest_for(item, "teardown") del item._store[caplog_records_key] del item._store[caplog_handler_key] @hookimpl def pytest_runtest_logfinish(self) -> None: self.log_cli_handler.set_when("finish") @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionfinish(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionfinish") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl def pytest_unconfigure(self) -> None: # Close the FileHandler explicitly. # (logging.shutdown might have lost the weakref?!) self.log_file_handler.close() class _FileHandler(logging.FileHandler): """A logging FileHandler with pytest tweaks.""" def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingStreamHandler(logging.StreamHandler): """A logging StreamHandler used by the live logging feature: it will write a newline before the first log message in each test. During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured and won't appear in the terminal. """ # Officially stream needs to be a IO[str], but TerminalReporter # isn't. So force it. stream: TerminalReporter = None # type: ignore def __init__( self, terminal_reporter: TerminalReporter, capture_manager: Optional[CaptureManager], ) -> None: logging.StreamHandler.__init__(self, stream=terminal_reporter) # type: ignore[arg-type] self.capture_manager = capture_manager self.reset() self.set_when(None) self._test_outcome_written = False def reset(self) -> None: """Reset the handler; should be called before the start of each test.""" self._first_record_emitted = False def set_when(self, when: Optional[str]) -> None: """Prepare for the given test phase (setup/call/teardown).""" self._when = when self._section_name_shown = False if when == "start": self._test_outcome_written = False def emit(self, record: logging.LogRecord) -> None: ctx_manager = ( self.capture_manager.global_and_fixture_disabled() if self.capture_manager else nullcontext() ) with ctx_manager: if not self._first_record_emitted: self.stream.write("\n") self._first_record_emitted = True elif self._when in ("teardown", "finish"): if not self._test_outcome_written: self._test_outcome_written = True self.stream.write("\n") if not self._section_name_shown and self._when: self.stream.section("live log " + self._when, sep="-", bold=True) self._section_name_shown = True super().emit(record) def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingNullHandler(logging.NullHandler): """A logging handler used when live logging is disabled.""" def reset(self) -> None: pass def set_when(self, when: str) -> None: pass def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler.
pass
identifier_body
logging.py
"""Access and control log capturing.""" import logging import os import re import sys from contextlib import contextmanager from io import StringIO from pathlib import Path from typing import AbstractSet from typing import Dict from typing import Generator from typing import List from typing import Mapping from typing import Optional from typing import Tuple from typing import TypeVar from typing import Union from _pytest import nodes from _pytest._io import TerminalWriter from _pytest.capture import CaptureManager from _pytest.compat import final from _pytest.compat import nullcontext from _pytest.config import _strtobool from _pytest.config import Config from _pytest.config import create_terminal_writer from _pytest.config import hookimpl from _pytest.config import UsageError from _pytest.config.argparsing import Parser from _pytest.deprecated import check_ispytest from _pytest.fixtures import fixture from _pytest.fixtures import FixtureRequest from _pytest.main import Session from _pytest.store import StoreKey from _pytest.terminal import TerminalReporter DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S" _ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m") caplog_handler_key = StoreKey["LogCaptureHandler"]() caplog_records_key = StoreKey[Dict[str, List[logging.LogRecord]]]() def _remove_ansi_escape_sequences(text: str) -> str: return _ANSI_ESCAPE_SEQ.sub("", text) class ColoredLevelFormatter(logging.Formatter): """A logging formatter which colorizes the %(levelname)..s part of the log format passed to __init__.""" LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = { logging.CRITICAL: {"red"}, logging.ERROR: {"red", "bold"}, logging.WARNING: {"yellow"}, logging.WARN: {"yellow"}, logging.INFO: {"green"}, logging.DEBUG: {"purple"}, logging.NOTSET: set(), } LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)") def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._original_fmt = self._style._fmt self._level_to_fmt_mapping: Dict[int, str] = {} assert self._fmt is not None levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt) if not levelname_fmt_match: return levelname_fmt = levelname_fmt_match.group() for level, color_opts in self.LOGLEVEL_COLOROPTS.items(): formatted_levelname = levelname_fmt % { "levelname": logging.getLevelName(level) } # add ANSI escape sequences around the formatted levelname color_kwargs = {name: True for name in color_opts} colorized_formatted_levelname = terminalwriter.markup( formatted_levelname, **color_kwargs ) self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub( colorized_formatted_levelname, self._fmt ) def format(self, record: logging.LogRecord) -> str: fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) self._style._fmt = fmt return super().format(record) class PercentStyleMultiline(logging.PercentStyle): """A logging style with special support for multiline messages. If the message of a record consists of multiple lines, this style formats the message as if each line were logged separately. """ def __init__(self, fmt: str, auto_indent: Union[int, str, bool, None]) -> None: super().__init__(fmt) self._auto_indent = self._get_auto_indent(auto_indent) @staticmethod def _update_message( record_dict: Dict[str, object], message: str ) -> Dict[str, object]: tmp = record_dict.copy() tmp["message"] = message return tmp @staticmethod def _get_auto_indent(auto_indent_option: Union[int, str, bool, None]) -> int: """Determine the current auto indentation setting. Specify auto indent behavior (on/off/fixed) by passing in extra={"auto_indent": [value]} to the call to logging.log() or using a --log-auto-indent [value] command line or the log_auto_indent [value] config option. Default behavior is auto-indent off. Using the string "True" or "on" or the boolean True as the value turns auto indent on, using the string "False" or "off" or the boolean False or the int 0 turns it off, and specifying a positive integer fixes the indentation position to the value specified. Any other values for the option are invalid, and will silently be converted to the default. :param None|bool|int|str auto_indent_option: User specified option for indentation from command line, config or extra kwarg. Accepts int, bool or str. str option accepts the same range of values as boolean config options, as well as positive integers represented in str form. :returns: Indentation value, which can be -1 (automatically determine indentation) or 0 (auto-indent turned off) or >0 (explicitly set indentation position). """ if auto_indent_option is None: return 0 elif isinstance(auto_indent_option, bool): if auto_indent_option: return -1 else: return 0 elif isinstance(auto_indent_option, int): return int(auto_indent_option) elif isinstance(auto_indent_option, str): try: return int(auto_indent_option) except ValueError: pass try: if _strtobool(auto_indent_option): return -1 except ValueError: return 0 return 0 def format(self, record: logging.LogRecord) -> str: if "\n" in record.message: if hasattr(record, "auto_indent"): # Passed in from the "extra={}" kwarg on the call to logging.log(). auto_indent = self._get_auto_indent(record.auto_indent) # type: ignore[attr-defined] else: auto_indent = self._auto_indent if auto_indent: lines = record.message.splitlines() formatted = self._fmt % self._update_message(record.__dict__, lines[0]) if auto_indent < 0: indentation = _remove_ansi_escape_sequences(formatted).find( lines[0] ) else: # Optimizes logging by allowing a fixed indentation. indentation = auto_indent lines[0] = formatted return ("\n" + " " * indentation).join(lines) return self._fmt % record.__dict__ def get_option_ini(config: Config, *names: str): for name in names: ret = config.getoption(name) # 'default' arg won't work as expected if ret is None: ret = config.getini(name) if ret: return ret def pytest_addoption(parser: Parser) -> None: """Add options to control log capturing.""" group = parser.getgroup("logging") def add_option_ini(option, dest, default=None, type=None, **kwargs): parser.addini( dest, default=default, type=type, help="default value for " + option ) group.addoption(option, dest=dest, **kwargs) add_option_ini( "--log-level", dest="log_level", default=None, metavar="LEVEL", help=( "level of messages to catch/display.\n" "Not set by default, so it depends on the root/parent log handler's" ' effective level, where it is "WARNING" by default.' ), ) add_option_ini( "--log-format", dest="log_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-date-format", dest="log_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) parser.addini( "log_cli", default=False, type="bool", help='enable log display during test run (also known as "live logging").', ) add_option_ini( "--log-cli-level", dest="log_cli_level", default=None, help="cli logging level." ) add_option_ini( "--log-cli-format", dest="log_cli_format", default=None, help="log format as used by the logging module.", ) add_option_ini(
dest="log_cli_date_format", default=None, help="log date format as used by the logging module.", ) add_option_ini( "--log-file", dest="log_file", default=None, help="path to a file when logging will be written to.", ) add_option_ini( "--log-file-level", dest="log_file_level", default=None, help="log file logging level.", ) add_option_ini( "--log-file-format", dest="log_file_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-file-date-format", dest="log_file_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) add_option_ini( "--log-auto-indent", dest="log_auto_indent", default=None, help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.", ) _HandlerType = TypeVar("_HandlerType", bound=logging.Handler) # Not using @contextmanager for performance reasons. class catching_logs: """Context manager that prepares the whole logging machinery properly.""" __slots__ = ("handler", "level", "orig_level") def __init__(self, handler: _HandlerType, level: Optional[int] = None) -> None: self.handler = handler self.level = level def __enter__(self): root_logger = logging.getLogger() if self.level is not None: self.handler.setLevel(self.level) root_logger.addHandler(self.handler) if self.level is not None: self.orig_level = root_logger.level root_logger.setLevel(min(self.orig_level, self.level)) return self.handler def __exit__(self, type, value, traceback): root_logger = logging.getLogger() if self.level is not None: root_logger.setLevel(self.orig_level) root_logger.removeHandler(self.handler) class LogCaptureHandler(logging.StreamHandler): """A logging handler that stores log records and the log text.""" stream: StringIO def __init__(self) -> None: """Create a new log handler.""" super().__init__(StringIO()) self.records: List[logging.LogRecord] = [] def emit(self, record: logging.LogRecord) -> None: """Keep the log records in a list in addition to the log text.""" self.records.append(record) super().emit(record) def reset(self) -> None: self.records = [] self.stream = StringIO() def handleError(self, record: logging.LogRecord) -> None: if logging.raiseExceptions: # Fail the test if the log message is bad (emit failed). # The default behavior of logging is to print "Logging error" # to stderr with the call stack and some extra details. # pytest wants to make such mistakes visible during testing. raise @final class LogCaptureFixture: """Provides access and control of log capturing.""" def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: check_ispytest(_ispytest) self._item = item self._initial_handler_level: Optional[int] = None # Dict of log name -> log level. self._initial_logger_levels: Dict[Optional[str], int] = {} def _finalize(self) -> None: """Finalize the fixture. This restores the log levels changed by :meth:`set_level`. """ # Restore log levels. if self._initial_handler_level is not None: self.handler.setLevel(self._initial_handler_level) for logger_name, level in self._initial_logger_levels.items(): logger = logging.getLogger(logger_name) logger.setLevel(level) @property def handler(self) -> LogCaptureHandler: """Get the logging handler used by the fixture. :rtype: LogCaptureHandler """ return self._item._store[caplog_handler_key] def get_records(self, when: str) -> List[logging.LogRecord]: """Get the logging records for one of the possible test phases. :param str when: Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown". :returns: The list of captured records at the given stage. :rtype: List[logging.LogRecord] .. versionadded:: 3.4 """ return self._item._store[caplog_records_key].get(when, []) @property def text(self) -> str: """The formatted log text.""" return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) @property def records(self) -> List[logging.LogRecord]: """The list of log records.""" return self.handler.records @property def record_tuples(self) -> List[Tuple[str, int, str]]: """A list of a stripped down version of log records intended for use in assertion comparison. The format of the tuple is: (logger_name, log_level, message) """ return [(r.name, r.levelno, r.getMessage()) for r in self.records] @property def messages(self) -> List[str]: """A list of format-interpolated log messages. Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list are all interpolated. Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with levels, timestamps, etc, making exact comparisons more reliable. Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments to the logging functions) is not included, as this is added by the formatter in the handler. .. versionadded:: 3.7 """ return [r.getMessage() for r in self.records] def clear(self) -> None: """Reset the list of log records and the captured log text.""" self.handler.reset() def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None: """Set the level of a logger for the duration of a test. .. versionchanged:: 3.4 The levels of the loggers changed by this function will be restored to their initial values at the end of the test. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) # Save the original log-level to restore it during teardown. self._initial_logger_levels.setdefault(logger, logger_obj.level) logger_obj.setLevel(level) if self._initial_handler_level is None: self._initial_handler_level = self.handler.level self.handler.setLevel(level) @contextmanager def at_level( self, level: int, logger: Optional[str] = None ) -> Generator[None, None, None]: """Context manager that sets the level for capturing of logs. After the end of the 'with' statement the level is restored to its original value. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) orig_level = logger_obj.level logger_obj.setLevel(level) handler_orig_level = self.handler.level self.handler.setLevel(level) try: yield finally: logger_obj.setLevel(orig_level) self.handler.setLevel(handler_orig_level) @fixture def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture, None, None]: """Access and control log capturing. Captured logs are available through the following properties/methods:: * caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string """ result = LogCaptureFixture(request.node, _ispytest=True) yield result result._finalize() def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]: for setting_name in setting_names: log_level = config.getoption(setting_name) if log_level is None: log_level = config.getini(setting_name) if log_level: break else: return None if isinstance(log_level, str): log_level = log_level.upper() try: return int(getattr(logging, log_level, log_level)) except ValueError as e: # Python logging does not recognise this as a logging level raise UsageError( "'{}' is not recognized as a logging level name for " "'{}'. Please consider passing the " "logging level num instead.".format(log_level, setting_name) ) from e # run after terminalreporter/capturemanager are configured @hookimpl(trylast=True) def pytest_configure(config: Config) -> None: config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") class LoggingPlugin: """Attaches to the logging module and captures log messages for each test.""" def __init__(self, config: Config) -> None: """Create a new plugin to capture log messages. The formatter can be safely shared across all handlers so create a single one for the entire test session here. """ self._config = config # Report logging. self.formatter = self._create_formatter( get_option_ini(config, "log_format"), get_option_ini(config, "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_level = get_log_level_for_setting(config, "log_level") self.caplog_handler = LogCaptureHandler() self.caplog_handler.setFormatter(self.formatter) self.report_handler = LogCaptureHandler() self.report_handler.setFormatter(self.formatter) # File logging. self.log_file_level = get_log_level_for_setting(config, "log_file_level") log_file = get_option_ini(config, "log_file") or os.devnull if log_file != os.devnull: directory = os.path.dirname(os.path.abspath(log_file)) if not os.path.isdir(directory): os.makedirs(directory) self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8") log_file_format = get_option_ini(config, "log_file_format", "log_format") log_file_date_format = get_option_ini( config, "log_file_date_format", "log_date_format" ) log_file_formatter = logging.Formatter( log_file_format, datefmt=log_file_date_format ) self.log_file_handler.setFormatter(log_file_formatter) # CLI/live logging. self.log_cli_level = get_log_level_for_setting( config, "log_cli_level", "log_level" ) if self._log_cli_enabled(): terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") capture_manager = config.pluginmanager.get_plugin("capturemanager") # if capturemanager plugin is disabled, live logging still works. self.log_cli_handler: Union[ _LiveLoggingStreamHandler, _LiveLoggingNullHandler ] = _LiveLoggingStreamHandler(terminal_reporter, capture_manager) else: self.log_cli_handler = _LiveLoggingNullHandler() log_cli_formatter = self._create_formatter( get_option_ini(config, "log_cli_format", "log_format"), get_option_ini(config, "log_cli_date_format", "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_cli_handler.setFormatter(log_cli_formatter) def _create_formatter(self, log_format, log_date_format, auto_indent): # Color option doesn't exist if terminal plugin is disabled. color = getattr(self._config.option, "color", "no") if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search( log_format ): formatter: logging.Formatter = ColoredLevelFormatter( create_terminal_writer(self._config), log_format, log_date_format ) else: formatter = logging.Formatter(log_format, log_date_format) formatter._style = PercentStyleMultiline( formatter._style._fmt, auto_indent=auto_indent ) return formatter def set_log_path(self, fname: str) -> None: """Set the filename parameter for Logging.FileHandler(). Creates parent directory if it does not exist. .. warning:: This is an experimental API. """ fpath = Path(fname) if not fpath.is_absolute(): fpath = self._config.rootpath / fpath if not fpath.parent.exists(): fpath.parent.mkdir(exist_ok=True, parents=True) stream = fpath.open(mode="w", encoding="UTF-8") if sys.version_info >= (3, 7): old_stream = self.log_file_handler.setStream(stream) else: old_stream = self.log_file_handler.stream self.log_file_handler.acquire() try: self.log_file_handler.flush() self.log_file_handler.stream = stream finally: self.log_file_handler.release() if old_stream: old_stream.close() def _log_cli_enabled(self): """Return whether live logging is enabled.""" enabled = self._config.getoption( "--log-cli-level" ) is not None or self._config.getini("log_cli") if not enabled: return False terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter") if terminal_reporter is None: # terminal reporter is disabled e.g. by pytest-xdist. return False return True @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionstart(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionstart") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True, tryfirst=True) def pytest_collection(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("collection") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True) def pytest_runtestloop(self, session: Session) -> Generator[None, None, None]: if session.config.option.collectonly: yield return if self._log_cli_enabled() and self._config.getoption("verbose") < 1: # The verbose flag is needed to avoid messy test progress output. self._config.option.verbose = 1 with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield # Run all the tests. @hookimpl def pytest_runtest_logstart(self) -> None: self.log_cli_handler.reset() self.log_cli_handler.set_when("start") @hookimpl def pytest_runtest_logreport(self) -> None: self.log_cli_handler.set_when("logreport") def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]: """Implement the internals of the pytest_runtest_xxx() hooks.""" with catching_logs( self.caplog_handler, level=self.log_level, ) as caplog_handler, catching_logs( self.report_handler, level=self.log_level, ) as report_handler: caplog_handler.reset() report_handler.reset() item._store[caplog_records_key][when] = caplog_handler.records item._store[caplog_handler_key] = caplog_handler yield log = report_handler.stream.getvalue().strip() item.add_report_section(when, "log", log) @hookimpl(hookwrapper=True) def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("setup") empty: Dict[str, List[logging.LogRecord]] = {} item._store[caplog_records_key] = empty yield from self._runtest_for(item, "setup") @hookimpl(hookwrapper=True) def pytest_runtest_call(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("call") yield from self._runtest_for(item, "call") @hookimpl(hookwrapper=True) def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("teardown") yield from self._runtest_for(item, "teardown") del item._store[caplog_records_key] del item._store[caplog_handler_key] @hookimpl def pytest_runtest_logfinish(self) -> None: self.log_cli_handler.set_when("finish") @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionfinish(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionfinish") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl def pytest_unconfigure(self) -> None: # Close the FileHandler explicitly. # (logging.shutdown might have lost the weakref?!) self.log_file_handler.close() class _FileHandler(logging.FileHandler): """A logging FileHandler with pytest tweaks.""" def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingStreamHandler(logging.StreamHandler): """A logging StreamHandler used by the live logging feature: it will write a newline before the first log message in each test. During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured and won't appear in the terminal. """ # Officially stream needs to be a IO[str], but TerminalReporter # isn't. So force it. stream: TerminalReporter = None # type: ignore def __init__( self, terminal_reporter: TerminalReporter, capture_manager: Optional[CaptureManager], ) -> None: logging.StreamHandler.__init__(self, stream=terminal_reporter) # type: ignore[arg-type] self.capture_manager = capture_manager self.reset() self.set_when(None) self._test_outcome_written = False def reset(self) -> None: """Reset the handler; should be called before the start of each test.""" self._first_record_emitted = False def set_when(self, when: Optional[str]) -> None: """Prepare for the given test phase (setup/call/teardown).""" self._when = when self._section_name_shown = False if when == "start": self._test_outcome_written = False def emit(self, record: logging.LogRecord) -> None: ctx_manager = ( self.capture_manager.global_and_fixture_disabled() if self.capture_manager else nullcontext() ) with ctx_manager: if not self._first_record_emitted: self.stream.write("\n") self._first_record_emitted = True elif self._when in ("teardown", "finish"): if not self._test_outcome_written: self._test_outcome_written = True self.stream.write("\n") if not self._section_name_shown and self._when: self.stream.section("live log " + self._when, sep="-", bold=True) self._section_name_shown = True super().emit(record) def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingNullHandler(logging.NullHandler): """A logging handler used when live logging is disabled.""" def reset(self) -> None: pass def set_when(self, when: str) -> None: pass def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass
"--log-cli-date-format",
random_line_split
logging.py
"""Access and control log capturing.""" import logging import os import re import sys from contextlib import contextmanager from io import StringIO from pathlib import Path from typing import AbstractSet from typing import Dict from typing import Generator from typing import List from typing import Mapping from typing import Optional from typing import Tuple from typing import TypeVar from typing import Union from _pytest import nodes from _pytest._io import TerminalWriter from _pytest.capture import CaptureManager from _pytest.compat import final from _pytest.compat import nullcontext from _pytest.config import _strtobool from _pytest.config import Config from _pytest.config import create_terminal_writer from _pytest.config import hookimpl from _pytest.config import UsageError from _pytest.config.argparsing import Parser from _pytest.deprecated import check_ispytest from _pytest.fixtures import fixture from _pytest.fixtures import FixtureRequest from _pytest.main import Session from _pytest.store import StoreKey from _pytest.terminal import TerminalReporter DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S" _ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m") caplog_handler_key = StoreKey["LogCaptureHandler"]() caplog_records_key = StoreKey[Dict[str, List[logging.LogRecord]]]() def _remove_ansi_escape_sequences(text: str) -> str: return _ANSI_ESCAPE_SEQ.sub("", text) class ColoredLevelFormatter(logging.Formatter): """A logging formatter which colorizes the %(levelname)..s part of the log format passed to __init__.""" LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = { logging.CRITICAL: {"red"}, logging.ERROR: {"red", "bold"}, logging.WARNING: {"yellow"}, logging.WARN: {"yellow"}, logging.INFO: {"green"}, logging.DEBUG: {"purple"}, logging.NOTSET: set(), } LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)") def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._original_fmt = self._style._fmt self._level_to_fmt_mapping: Dict[int, str] = {} assert self._fmt is not None levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt) if not levelname_fmt_match: return levelname_fmt = levelname_fmt_match.group() for level, color_opts in self.LOGLEVEL_COLOROPTS.items(): formatted_levelname = levelname_fmt % { "levelname": logging.getLevelName(level) } # add ANSI escape sequences around the formatted levelname color_kwargs = {name: True for name in color_opts} colorized_formatted_levelname = terminalwriter.markup( formatted_levelname, **color_kwargs ) self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub( colorized_formatted_levelname, self._fmt ) def format(self, record: logging.LogRecord) -> str: fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) self._style._fmt = fmt return super().format(record) class PercentStyleMultiline(logging.PercentStyle): """A logging style with special support for multiline messages. If the message of a record consists of multiple lines, this style formats the message as if each line were logged separately. """ def __init__(self, fmt: str, auto_indent: Union[int, str, bool, None]) -> None: super().__init__(fmt) self._auto_indent = self._get_auto_indent(auto_indent) @staticmethod def _update_message( record_dict: Dict[str, object], message: str ) -> Dict[str, object]: tmp = record_dict.copy() tmp["message"] = message return tmp @staticmethod def _get_auto_indent(auto_indent_option: Union[int, str, bool, None]) -> int: """Determine the current auto indentation setting. Specify auto indent behavior (on/off/fixed) by passing in extra={"auto_indent": [value]} to the call to logging.log() or using a --log-auto-indent [value] command line or the log_auto_indent [value] config option. Default behavior is auto-indent off. Using the string "True" or "on" or the boolean True as the value turns auto indent on, using the string "False" or "off" or the boolean False or the int 0 turns it off, and specifying a positive integer fixes the indentation position to the value specified. Any other values for the option are invalid, and will silently be converted to the default. :param None|bool|int|str auto_indent_option: User specified option for indentation from command line, config or extra kwarg. Accepts int, bool or str. str option accepts the same range of values as boolean config options, as well as positive integers represented in str form. :returns: Indentation value, which can be -1 (automatically determine indentation) or 0 (auto-indent turned off) or >0 (explicitly set indentation position). """ if auto_indent_option is None: return 0 elif isinstance(auto_indent_option, bool): if auto_indent_option: return -1 else: return 0 elif isinstance(auto_indent_option, int): return int(auto_indent_option) elif isinstance(auto_indent_option, str): try: return int(auto_indent_option) except ValueError: pass try: if _strtobool(auto_indent_option): return -1 except ValueError: return 0 return 0 def format(self, record: logging.LogRecord) -> str: if "\n" in record.message: if hasattr(record, "auto_indent"): # Passed in from the "extra={}" kwarg on the call to logging.log(). auto_indent = self._get_auto_indent(record.auto_indent) # type: ignore[attr-defined] else: auto_indent = self._auto_indent if auto_indent: lines = record.message.splitlines() formatted = self._fmt % self._update_message(record.__dict__, lines[0]) if auto_indent < 0: indentation = _remove_ansi_escape_sequences(formatted).find( lines[0] ) else: # Optimizes logging by allowing a fixed indentation. indentation = auto_indent lines[0] = formatted return ("\n" + " " * indentation).join(lines) return self._fmt % record.__dict__ def get_option_ini(config: Config, *names: str): for name in names: ret = config.getoption(name) # 'default' arg won't work as expected if ret is None: ret = config.getini(name) if ret: return ret def pytest_addoption(parser: Parser) -> None: """Add options to control log capturing.""" group = parser.getgroup("logging") def add_option_ini(option, dest, default=None, type=None, **kwargs): parser.addini( dest, default=default, type=type, help="default value for " + option ) group.addoption(option, dest=dest, **kwargs) add_option_ini( "--log-level", dest="log_level", default=None, metavar="LEVEL", help=( "level of messages to catch/display.\n" "Not set by default, so it depends on the root/parent log handler's" ' effective level, where it is "WARNING" by default.' ), ) add_option_ini( "--log-format", dest="log_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-date-format", dest="log_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) parser.addini( "log_cli", default=False, type="bool", help='enable log display during test run (also known as "live logging").', ) add_option_ini( "--log-cli-level", dest="log_cli_level", default=None, help="cli logging level." ) add_option_ini( "--log-cli-format", dest="log_cli_format", default=None, help="log format as used by the logging module.", ) add_option_ini( "--log-cli-date-format", dest="log_cli_date_format", default=None, help="log date format as used by the logging module.", ) add_option_ini( "--log-file", dest="log_file", default=None, help="path to a file when logging will be written to.", ) add_option_ini( "--log-file-level", dest="log_file_level", default=None, help="log file logging level.", ) add_option_ini( "--log-file-format", dest="log_file_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-file-date-format", dest="log_file_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) add_option_ini( "--log-auto-indent", dest="log_auto_indent", default=None, help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.", ) _HandlerType = TypeVar("_HandlerType", bound=logging.Handler) # Not using @contextmanager for performance reasons. class catching_logs: """Context manager that prepares the whole logging machinery properly.""" __slots__ = ("handler", "level", "orig_level") def __init__(self, handler: _HandlerType, level: Optional[int] = None) -> None: self.handler = handler self.level = level def __enter__(self): root_logger = logging.getLogger() if self.level is not None:
root_logger.addHandler(self.handler) if self.level is not None: self.orig_level = root_logger.level root_logger.setLevel(min(self.orig_level, self.level)) return self.handler def __exit__(self, type, value, traceback): root_logger = logging.getLogger() if self.level is not None: root_logger.setLevel(self.orig_level) root_logger.removeHandler(self.handler) class LogCaptureHandler(logging.StreamHandler): """A logging handler that stores log records and the log text.""" stream: StringIO def __init__(self) -> None: """Create a new log handler.""" super().__init__(StringIO()) self.records: List[logging.LogRecord] = [] def emit(self, record: logging.LogRecord) -> None: """Keep the log records in a list in addition to the log text.""" self.records.append(record) super().emit(record) def reset(self) -> None: self.records = [] self.stream = StringIO() def handleError(self, record: logging.LogRecord) -> None: if logging.raiseExceptions: # Fail the test if the log message is bad (emit failed). # The default behavior of logging is to print "Logging error" # to stderr with the call stack and some extra details. # pytest wants to make such mistakes visible during testing. raise @final class LogCaptureFixture: """Provides access and control of log capturing.""" def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: check_ispytest(_ispytest) self._item = item self._initial_handler_level: Optional[int] = None # Dict of log name -> log level. self._initial_logger_levels: Dict[Optional[str], int] = {} def _finalize(self) -> None: """Finalize the fixture. This restores the log levels changed by :meth:`set_level`. """ # Restore log levels. if self._initial_handler_level is not None: self.handler.setLevel(self._initial_handler_level) for logger_name, level in self._initial_logger_levels.items(): logger = logging.getLogger(logger_name) logger.setLevel(level) @property def handler(self) -> LogCaptureHandler: """Get the logging handler used by the fixture. :rtype: LogCaptureHandler """ return self._item._store[caplog_handler_key] def get_records(self, when: str) -> List[logging.LogRecord]: """Get the logging records for one of the possible test phases. :param str when: Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown". :returns: The list of captured records at the given stage. :rtype: List[logging.LogRecord] .. versionadded:: 3.4 """ return self._item._store[caplog_records_key].get(when, []) @property def text(self) -> str: """The formatted log text.""" return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) @property def records(self) -> List[logging.LogRecord]: """The list of log records.""" return self.handler.records @property def record_tuples(self) -> List[Tuple[str, int, str]]: """A list of a stripped down version of log records intended for use in assertion comparison. The format of the tuple is: (logger_name, log_level, message) """ return [(r.name, r.levelno, r.getMessage()) for r in self.records] @property def messages(self) -> List[str]: """A list of format-interpolated log messages. Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list are all interpolated. Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with levels, timestamps, etc, making exact comparisons more reliable. Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments to the logging functions) is not included, as this is added by the formatter in the handler. .. versionadded:: 3.7 """ return [r.getMessage() for r in self.records] def clear(self) -> None: """Reset the list of log records and the captured log text.""" self.handler.reset() def set_level(self, level: Union[int, str], logger: Optional[str] = None) -> None: """Set the level of a logger for the duration of a test. .. versionchanged:: 3.4 The levels of the loggers changed by this function will be restored to their initial values at the end of the test. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) # Save the original log-level to restore it during teardown. self._initial_logger_levels.setdefault(logger, logger_obj.level) logger_obj.setLevel(level) if self._initial_handler_level is None: self._initial_handler_level = self.handler.level self.handler.setLevel(level) @contextmanager def at_level( self, level: int, logger: Optional[str] = None ) -> Generator[None, None, None]: """Context manager that sets the level for capturing of logs. After the end of the 'with' statement the level is restored to its original value. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) orig_level = logger_obj.level logger_obj.setLevel(level) handler_orig_level = self.handler.level self.handler.setLevel(level) try: yield finally: logger_obj.setLevel(orig_level) self.handler.setLevel(handler_orig_level) @fixture def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture, None, None]: """Access and control log capturing. Captured logs are available through the following properties/methods:: * caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string """ result = LogCaptureFixture(request.node, _ispytest=True) yield result result._finalize() def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]: for setting_name in setting_names: log_level = config.getoption(setting_name) if log_level is None: log_level = config.getini(setting_name) if log_level: break else: return None if isinstance(log_level, str): log_level = log_level.upper() try: return int(getattr(logging, log_level, log_level)) except ValueError as e: # Python logging does not recognise this as a logging level raise UsageError( "'{}' is not recognized as a logging level name for " "'{}'. Please consider passing the " "logging level num instead.".format(log_level, setting_name) ) from e # run after terminalreporter/capturemanager are configured @hookimpl(trylast=True) def pytest_configure(config: Config) -> None: config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") class LoggingPlugin: """Attaches to the logging module and captures log messages for each test.""" def __init__(self, config: Config) -> None: """Create a new plugin to capture log messages. The formatter can be safely shared across all handlers so create a single one for the entire test session here. """ self._config = config # Report logging. self.formatter = self._create_formatter( get_option_ini(config, "log_format"), get_option_ini(config, "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_level = get_log_level_for_setting(config, "log_level") self.caplog_handler = LogCaptureHandler() self.caplog_handler.setFormatter(self.formatter) self.report_handler = LogCaptureHandler() self.report_handler.setFormatter(self.formatter) # File logging. self.log_file_level = get_log_level_for_setting(config, "log_file_level") log_file = get_option_ini(config, "log_file") or os.devnull if log_file != os.devnull: directory = os.path.dirname(os.path.abspath(log_file)) if not os.path.isdir(directory): os.makedirs(directory) self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8") log_file_format = get_option_ini(config, "log_file_format", "log_format") log_file_date_format = get_option_ini( config, "log_file_date_format", "log_date_format" ) log_file_formatter = logging.Formatter( log_file_format, datefmt=log_file_date_format ) self.log_file_handler.setFormatter(log_file_formatter) # CLI/live logging. self.log_cli_level = get_log_level_for_setting( config, "log_cli_level", "log_level" ) if self._log_cli_enabled(): terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") capture_manager = config.pluginmanager.get_plugin("capturemanager") # if capturemanager plugin is disabled, live logging still works. self.log_cli_handler: Union[ _LiveLoggingStreamHandler, _LiveLoggingNullHandler ] = _LiveLoggingStreamHandler(terminal_reporter, capture_manager) else: self.log_cli_handler = _LiveLoggingNullHandler() log_cli_formatter = self._create_formatter( get_option_ini(config, "log_cli_format", "log_format"), get_option_ini(config, "log_cli_date_format", "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_cli_handler.setFormatter(log_cli_formatter) def _create_formatter(self, log_format, log_date_format, auto_indent): # Color option doesn't exist if terminal plugin is disabled. color = getattr(self._config.option, "color", "no") if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search( log_format ): formatter: logging.Formatter = ColoredLevelFormatter( create_terminal_writer(self._config), log_format, log_date_format ) else: formatter = logging.Formatter(log_format, log_date_format) formatter._style = PercentStyleMultiline( formatter._style._fmt, auto_indent=auto_indent ) return formatter def set_log_path(self, fname: str) -> None: """Set the filename parameter for Logging.FileHandler(). Creates parent directory if it does not exist. .. warning:: This is an experimental API. """ fpath = Path(fname) if not fpath.is_absolute(): fpath = self._config.rootpath / fpath if not fpath.parent.exists(): fpath.parent.mkdir(exist_ok=True, parents=True) stream = fpath.open(mode="w", encoding="UTF-8") if sys.version_info >= (3, 7): old_stream = self.log_file_handler.setStream(stream) else: old_stream = self.log_file_handler.stream self.log_file_handler.acquire() try: self.log_file_handler.flush() self.log_file_handler.stream = stream finally: self.log_file_handler.release() if old_stream: old_stream.close() def _log_cli_enabled(self): """Return whether live logging is enabled.""" enabled = self._config.getoption( "--log-cli-level" ) is not None or self._config.getini("log_cli") if not enabled: return False terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter") if terminal_reporter is None: # terminal reporter is disabled e.g. by pytest-xdist. return False return True @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionstart(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionstart") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True, tryfirst=True) def pytest_collection(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("collection") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True) def pytest_runtestloop(self, session: Session) -> Generator[None, None, None]: if session.config.option.collectonly: yield return if self._log_cli_enabled() and self._config.getoption("verbose") < 1: # The verbose flag is needed to avoid messy test progress output. self._config.option.verbose = 1 with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield # Run all the tests. @hookimpl def pytest_runtest_logstart(self) -> None: self.log_cli_handler.reset() self.log_cli_handler.set_when("start") @hookimpl def pytest_runtest_logreport(self) -> None: self.log_cli_handler.set_when("logreport") def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]: """Implement the internals of the pytest_runtest_xxx() hooks.""" with catching_logs( self.caplog_handler, level=self.log_level, ) as caplog_handler, catching_logs( self.report_handler, level=self.log_level, ) as report_handler: caplog_handler.reset() report_handler.reset() item._store[caplog_records_key][when] = caplog_handler.records item._store[caplog_handler_key] = caplog_handler yield log = report_handler.stream.getvalue().strip() item.add_report_section(when, "log", log) @hookimpl(hookwrapper=True) def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("setup") empty: Dict[str, List[logging.LogRecord]] = {} item._store[caplog_records_key] = empty yield from self._runtest_for(item, "setup") @hookimpl(hookwrapper=True) def pytest_runtest_call(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("call") yield from self._runtest_for(item, "call") @hookimpl(hookwrapper=True) def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("teardown") yield from self._runtest_for(item, "teardown") del item._store[caplog_records_key] del item._store[caplog_handler_key] @hookimpl def pytest_runtest_logfinish(self) -> None: self.log_cli_handler.set_when("finish") @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionfinish(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionfinish") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl def pytest_unconfigure(self) -> None: # Close the FileHandler explicitly. # (logging.shutdown might have lost the weakref?!) self.log_file_handler.close() class _FileHandler(logging.FileHandler): """A logging FileHandler with pytest tweaks.""" def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingStreamHandler(logging.StreamHandler): """A logging StreamHandler used by the live logging feature: it will write a newline before the first log message in each test. During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured and won't appear in the terminal. """ # Officially stream needs to be a IO[str], but TerminalReporter # isn't. So force it. stream: TerminalReporter = None # type: ignore def __init__( self, terminal_reporter: TerminalReporter, capture_manager: Optional[CaptureManager], ) -> None: logging.StreamHandler.__init__(self, stream=terminal_reporter) # type: ignore[arg-type] self.capture_manager = capture_manager self.reset() self.set_when(None) self._test_outcome_written = False def reset(self) -> None: """Reset the handler; should be called before the start of each test.""" self._first_record_emitted = False def set_when(self, when: Optional[str]) -> None: """Prepare for the given test phase (setup/call/teardown).""" self._when = when self._section_name_shown = False if when == "start": self._test_outcome_written = False def emit(self, record: logging.LogRecord) -> None: ctx_manager = ( self.capture_manager.global_and_fixture_disabled() if self.capture_manager else nullcontext() ) with ctx_manager: if not self._first_record_emitted: self.stream.write("\n") self._first_record_emitted = True elif self._when in ("teardown", "finish"): if not self._test_outcome_written: self._test_outcome_written = True self.stream.write("\n") if not self._section_name_shown and self._when: self.stream.section("live log " + self._when, sep="-", bold=True) self._section_name_shown = True super().emit(record) def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingNullHandler(logging.NullHandler): """A logging handler used when live logging is disabled.""" def reset(self) -> None: pass def set_when(self, when: str) -> None: pass def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass
self.handler.setLevel(self.level)
conditional_block
logging.py
"""Access and control log capturing.""" import logging import os import re import sys from contextlib import contextmanager from io import StringIO from pathlib import Path from typing import AbstractSet from typing import Dict from typing import Generator from typing import List from typing import Mapping from typing import Optional from typing import Tuple from typing import TypeVar from typing import Union from _pytest import nodes from _pytest._io import TerminalWriter from _pytest.capture import CaptureManager from _pytest.compat import final from _pytest.compat import nullcontext from _pytest.config import _strtobool from _pytest.config import Config from _pytest.config import create_terminal_writer from _pytest.config import hookimpl from _pytest.config import UsageError from _pytest.config.argparsing import Parser from _pytest.deprecated import check_ispytest from _pytest.fixtures import fixture from _pytest.fixtures import FixtureRequest from _pytest.main import Session from _pytest.store import StoreKey from _pytest.terminal import TerminalReporter DEFAULT_LOG_FORMAT = "%(levelname)-8s %(name)s:%(filename)s:%(lineno)d %(message)s" DEFAULT_LOG_DATE_FORMAT = "%H:%M:%S" _ANSI_ESCAPE_SEQ = re.compile(r"\x1b\[[\d;]+m") caplog_handler_key = StoreKey["LogCaptureHandler"]() caplog_records_key = StoreKey[Dict[str, List[logging.LogRecord]]]() def _remove_ansi_escape_sequences(text: str) -> str: return _ANSI_ESCAPE_SEQ.sub("", text) class ColoredLevelFormatter(logging.Formatter): """A logging formatter which colorizes the %(levelname)..s part of the log format passed to __init__.""" LOGLEVEL_COLOROPTS: Mapping[int, AbstractSet[str]] = { logging.CRITICAL: {"red"}, logging.ERROR: {"red", "bold"}, logging.WARNING: {"yellow"}, logging.WARN: {"yellow"}, logging.INFO: {"green"}, logging.DEBUG: {"purple"}, logging.NOTSET: set(), } LEVELNAME_FMT_REGEX = re.compile(r"%\(levelname\)([+-.]?\d*s)") def __init__(self, terminalwriter: TerminalWriter, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._original_fmt = self._style._fmt self._level_to_fmt_mapping: Dict[int, str] = {} assert self._fmt is not None levelname_fmt_match = self.LEVELNAME_FMT_REGEX.search(self._fmt) if not levelname_fmt_match: return levelname_fmt = levelname_fmt_match.group() for level, color_opts in self.LOGLEVEL_COLOROPTS.items(): formatted_levelname = levelname_fmt % { "levelname": logging.getLevelName(level) } # add ANSI escape sequences around the formatted levelname color_kwargs = {name: True for name in color_opts} colorized_formatted_levelname = terminalwriter.markup( formatted_levelname, **color_kwargs ) self._level_to_fmt_mapping[level] = self.LEVELNAME_FMT_REGEX.sub( colorized_formatted_levelname, self._fmt ) def format(self, record: logging.LogRecord) -> str: fmt = self._level_to_fmt_mapping.get(record.levelno, self._original_fmt) self._style._fmt = fmt return super().format(record) class PercentStyleMultiline(logging.PercentStyle): """A logging style with special support for multiline messages. If the message of a record consists of multiple lines, this style formats the message as if each line were logged separately. """ def __init__(self, fmt: str, auto_indent: Union[int, str, bool, None]) -> None: super().__init__(fmt) self._auto_indent = self._get_auto_indent(auto_indent) @staticmethod def _update_message( record_dict: Dict[str, object], message: str ) -> Dict[str, object]: tmp = record_dict.copy() tmp["message"] = message return tmp @staticmethod def _get_auto_indent(auto_indent_option: Union[int, str, bool, None]) -> int: """Determine the current auto indentation setting. Specify auto indent behavior (on/off/fixed) by passing in extra={"auto_indent": [value]} to the call to logging.log() or using a --log-auto-indent [value] command line or the log_auto_indent [value] config option. Default behavior is auto-indent off. Using the string "True" or "on" or the boolean True as the value turns auto indent on, using the string "False" or "off" or the boolean False or the int 0 turns it off, and specifying a positive integer fixes the indentation position to the value specified. Any other values for the option are invalid, and will silently be converted to the default. :param None|bool|int|str auto_indent_option: User specified option for indentation from command line, config or extra kwarg. Accepts int, bool or str. str option accepts the same range of values as boolean config options, as well as positive integers represented in str form. :returns: Indentation value, which can be -1 (automatically determine indentation) or 0 (auto-indent turned off) or >0 (explicitly set indentation position). """ if auto_indent_option is None: return 0 elif isinstance(auto_indent_option, bool): if auto_indent_option: return -1 else: return 0 elif isinstance(auto_indent_option, int): return int(auto_indent_option) elif isinstance(auto_indent_option, str): try: return int(auto_indent_option) except ValueError: pass try: if _strtobool(auto_indent_option): return -1 except ValueError: return 0 return 0 def format(self, record: logging.LogRecord) -> str: if "\n" in record.message: if hasattr(record, "auto_indent"): # Passed in from the "extra={}" kwarg on the call to logging.log(). auto_indent = self._get_auto_indent(record.auto_indent) # type: ignore[attr-defined] else: auto_indent = self._auto_indent if auto_indent: lines = record.message.splitlines() formatted = self._fmt % self._update_message(record.__dict__, lines[0]) if auto_indent < 0: indentation = _remove_ansi_escape_sequences(formatted).find( lines[0] ) else: # Optimizes logging by allowing a fixed indentation. indentation = auto_indent lines[0] = formatted return ("\n" + " " * indentation).join(lines) return self._fmt % record.__dict__ def get_option_ini(config: Config, *names: str): for name in names: ret = config.getoption(name) # 'default' arg won't work as expected if ret is None: ret = config.getini(name) if ret: return ret def pytest_addoption(parser: Parser) -> None: """Add options to control log capturing.""" group = parser.getgroup("logging") def add_option_ini(option, dest, default=None, type=None, **kwargs): parser.addini( dest, default=default, type=type, help="default value for " + option ) group.addoption(option, dest=dest, **kwargs) add_option_ini( "--log-level", dest="log_level", default=None, metavar="LEVEL", help=( "level of messages to catch/display.\n" "Not set by default, so it depends on the root/parent log handler's" ' effective level, where it is "WARNING" by default.' ), ) add_option_ini( "--log-format", dest="log_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-date-format", dest="log_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) parser.addini( "log_cli", default=False, type="bool", help='enable log display during test run (also known as "live logging").', ) add_option_ini( "--log-cli-level", dest="log_cli_level", default=None, help="cli logging level." ) add_option_ini( "--log-cli-format", dest="log_cli_format", default=None, help="log format as used by the logging module.", ) add_option_ini( "--log-cli-date-format", dest="log_cli_date_format", default=None, help="log date format as used by the logging module.", ) add_option_ini( "--log-file", dest="log_file", default=None, help="path to a file when logging will be written to.", ) add_option_ini( "--log-file-level", dest="log_file_level", default=None, help="log file logging level.", ) add_option_ini( "--log-file-format", dest="log_file_format", default=DEFAULT_LOG_FORMAT, help="log format as used by the logging module.", ) add_option_ini( "--log-file-date-format", dest="log_file_date_format", default=DEFAULT_LOG_DATE_FORMAT, help="log date format as used by the logging module.", ) add_option_ini( "--log-auto-indent", dest="log_auto_indent", default=None, help="Auto-indent multiline messages passed to the logging module. Accepts true|on, false|off or an integer.", ) _HandlerType = TypeVar("_HandlerType", bound=logging.Handler) # Not using @contextmanager for performance reasons. class catching_logs: """Context manager that prepares the whole logging machinery properly.""" __slots__ = ("handler", "level", "orig_level") def __init__(self, handler: _HandlerType, level: Optional[int] = None) -> None: self.handler = handler self.level = level def __enter__(self): root_logger = logging.getLogger() if self.level is not None: self.handler.setLevel(self.level) root_logger.addHandler(self.handler) if self.level is not None: self.orig_level = root_logger.level root_logger.setLevel(min(self.orig_level, self.level)) return self.handler def __exit__(self, type, value, traceback): root_logger = logging.getLogger() if self.level is not None: root_logger.setLevel(self.orig_level) root_logger.removeHandler(self.handler) class LogCaptureHandler(logging.StreamHandler): """A logging handler that stores log records and the log text.""" stream: StringIO def __init__(self) -> None: """Create a new log handler.""" super().__init__(StringIO()) self.records: List[logging.LogRecord] = [] def emit(self, record: logging.LogRecord) -> None: """Keep the log records in a list in addition to the log text.""" self.records.append(record) super().emit(record) def reset(self) -> None: self.records = [] self.stream = StringIO() def handleError(self, record: logging.LogRecord) -> None: if logging.raiseExceptions: # Fail the test if the log message is bad (emit failed). # The default behavior of logging is to print "Logging error" # to stderr with the call stack and some extra details. # pytest wants to make such mistakes visible during testing. raise @final class LogCaptureFixture: """Provides access and control of log capturing.""" def __init__(self, item: nodes.Node, *, _ispytest: bool = False) -> None: check_ispytest(_ispytest) self._item = item self._initial_handler_level: Optional[int] = None # Dict of log name -> log level. self._initial_logger_levels: Dict[Optional[str], int] = {} def _finalize(self) -> None: """Finalize the fixture. This restores the log levels changed by :meth:`set_level`. """ # Restore log levels. if self._initial_handler_level is not None: self.handler.setLevel(self._initial_handler_level) for logger_name, level in self._initial_logger_levels.items(): logger = logging.getLogger(logger_name) logger.setLevel(level) @property def handler(self) -> LogCaptureHandler: """Get the logging handler used by the fixture. :rtype: LogCaptureHandler """ return self._item._store[caplog_handler_key] def get_records(self, when: str) -> List[logging.LogRecord]: """Get the logging records for one of the possible test phases. :param str when: Which test phase to obtain the records from. Valid values are: "setup", "call" and "teardown". :returns: The list of captured records at the given stage. :rtype: List[logging.LogRecord] .. versionadded:: 3.4 """ return self._item._store[caplog_records_key].get(when, []) @property def text(self) -> str: """The formatted log text.""" return _remove_ansi_escape_sequences(self.handler.stream.getvalue()) @property def records(self) -> List[logging.LogRecord]: """The list of log records.""" return self.handler.records @property def record_tuples(self) -> List[Tuple[str, int, str]]: """A list of a stripped down version of log records intended for use in assertion comparison. The format of the tuple is: (logger_name, log_level, message) """ return [(r.name, r.levelno, r.getMessage()) for r in self.records] @property def messages(self) -> List[str]: """A list of format-interpolated log messages. Unlike 'records', which contains the format string and parameters for interpolation, log messages in this list are all interpolated. Unlike 'text', which contains the output from the handler, log messages in this list are unadorned with levels, timestamps, etc, making exact comparisons more reliable. Note that traceback or stack info (from :func:`logging.exception` or the `exc_info` or `stack_info` arguments to the logging functions) is not included, as this is added by the formatter in the handler. .. versionadded:: 3.7 """ return [r.getMessage() for r in self.records] def clear(self) -> None: """Reset the list of log records and the captured log text.""" self.handler.reset() def
(self, level: Union[int, str], logger: Optional[str] = None) -> None: """Set the level of a logger for the duration of a test. .. versionchanged:: 3.4 The levels of the loggers changed by this function will be restored to their initial values at the end of the test. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) # Save the original log-level to restore it during teardown. self._initial_logger_levels.setdefault(logger, logger_obj.level) logger_obj.setLevel(level) if self._initial_handler_level is None: self._initial_handler_level = self.handler.level self.handler.setLevel(level) @contextmanager def at_level( self, level: int, logger: Optional[str] = None ) -> Generator[None, None, None]: """Context manager that sets the level for capturing of logs. After the end of the 'with' statement the level is restored to its original value. :param int level: The level. :param str logger: The logger to update. If not given, the root logger. """ logger_obj = logging.getLogger(logger) orig_level = logger_obj.level logger_obj.setLevel(level) handler_orig_level = self.handler.level self.handler.setLevel(level) try: yield finally: logger_obj.setLevel(orig_level) self.handler.setLevel(handler_orig_level) @fixture def caplog(request: FixtureRequest) -> Generator[LogCaptureFixture, None, None]: """Access and control log capturing. Captured logs are available through the following properties/methods:: * caplog.messages -> list of format-interpolated log messages * caplog.text -> string containing formatted log output * caplog.records -> list of logging.LogRecord instances * caplog.record_tuples -> list of (logger_name, level, message) tuples * caplog.clear() -> clear captured records and formatted log output string """ result = LogCaptureFixture(request.node, _ispytest=True) yield result result._finalize() def get_log_level_for_setting(config: Config, *setting_names: str) -> Optional[int]: for setting_name in setting_names: log_level = config.getoption(setting_name) if log_level is None: log_level = config.getini(setting_name) if log_level: break else: return None if isinstance(log_level, str): log_level = log_level.upper() try: return int(getattr(logging, log_level, log_level)) except ValueError as e: # Python logging does not recognise this as a logging level raise UsageError( "'{}' is not recognized as a logging level name for " "'{}'. Please consider passing the " "logging level num instead.".format(log_level, setting_name) ) from e # run after terminalreporter/capturemanager are configured @hookimpl(trylast=True) def pytest_configure(config: Config) -> None: config.pluginmanager.register(LoggingPlugin(config), "logging-plugin") class LoggingPlugin: """Attaches to the logging module and captures log messages for each test.""" def __init__(self, config: Config) -> None: """Create a new plugin to capture log messages. The formatter can be safely shared across all handlers so create a single one for the entire test session here. """ self._config = config # Report logging. self.formatter = self._create_formatter( get_option_ini(config, "log_format"), get_option_ini(config, "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_level = get_log_level_for_setting(config, "log_level") self.caplog_handler = LogCaptureHandler() self.caplog_handler.setFormatter(self.formatter) self.report_handler = LogCaptureHandler() self.report_handler.setFormatter(self.formatter) # File logging. self.log_file_level = get_log_level_for_setting(config, "log_file_level") log_file = get_option_ini(config, "log_file") or os.devnull if log_file != os.devnull: directory = os.path.dirname(os.path.abspath(log_file)) if not os.path.isdir(directory): os.makedirs(directory) self.log_file_handler = _FileHandler(log_file, mode="w", encoding="UTF-8") log_file_format = get_option_ini(config, "log_file_format", "log_format") log_file_date_format = get_option_ini( config, "log_file_date_format", "log_date_format" ) log_file_formatter = logging.Formatter( log_file_format, datefmt=log_file_date_format ) self.log_file_handler.setFormatter(log_file_formatter) # CLI/live logging. self.log_cli_level = get_log_level_for_setting( config, "log_cli_level", "log_level" ) if self._log_cli_enabled(): terminal_reporter = config.pluginmanager.get_plugin("terminalreporter") capture_manager = config.pluginmanager.get_plugin("capturemanager") # if capturemanager plugin is disabled, live logging still works. self.log_cli_handler: Union[ _LiveLoggingStreamHandler, _LiveLoggingNullHandler ] = _LiveLoggingStreamHandler(terminal_reporter, capture_manager) else: self.log_cli_handler = _LiveLoggingNullHandler() log_cli_formatter = self._create_formatter( get_option_ini(config, "log_cli_format", "log_format"), get_option_ini(config, "log_cli_date_format", "log_date_format"), get_option_ini(config, "log_auto_indent"), ) self.log_cli_handler.setFormatter(log_cli_formatter) def _create_formatter(self, log_format, log_date_format, auto_indent): # Color option doesn't exist if terminal plugin is disabled. color = getattr(self._config.option, "color", "no") if color != "no" and ColoredLevelFormatter.LEVELNAME_FMT_REGEX.search( log_format ): formatter: logging.Formatter = ColoredLevelFormatter( create_terminal_writer(self._config), log_format, log_date_format ) else: formatter = logging.Formatter(log_format, log_date_format) formatter._style = PercentStyleMultiline( formatter._style._fmt, auto_indent=auto_indent ) return formatter def set_log_path(self, fname: str) -> None: """Set the filename parameter for Logging.FileHandler(). Creates parent directory if it does not exist. .. warning:: This is an experimental API. """ fpath = Path(fname) if not fpath.is_absolute(): fpath = self._config.rootpath / fpath if not fpath.parent.exists(): fpath.parent.mkdir(exist_ok=True, parents=True) stream = fpath.open(mode="w", encoding="UTF-8") if sys.version_info >= (3, 7): old_stream = self.log_file_handler.setStream(stream) else: old_stream = self.log_file_handler.stream self.log_file_handler.acquire() try: self.log_file_handler.flush() self.log_file_handler.stream = stream finally: self.log_file_handler.release() if old_stream: old_stream.close() def _log_cli_enabled(self): """Return whether live logging is enabled.""" enabled = self._config.getoption( "--log-cli-level" ) is not None or self._config.getini("log_cli") if not enabled: return False terminal_reporter = self._config.pluginmanager.get_plugin("terminalreporter") if terminal_reporter is None: # terminal reporter is disabled e.g. by pytest-xdist. return False return True @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionstart(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionstart") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True, tryfirst=True) def pytest_collection(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("collection") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl(hookwrapper=True) def pytest_runtestloop(self, session: Session) -> Generator[None, None, None]: if session.config.option.collectonly: yield return if self._log_cli_enabled() and self._config.getoption("verbose") < 1: # The verbose flag is needed to avoid messy test progress output. self._config.option.verbose = 1 with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield # Run all the tests. @hookimpl def pytest_runtest_logstart(self) -> None: self.log_cli_handler.reset() self.log_cli_handler.set_when("start") @hookimpl def pytest_runtest_logreport(self) -> None: self.log_cli_handler.set_when("logreport") def _runtest_for(self, item: nodes.Item, when: str) -> Generator[None, None, None]: """Implement the internals of the pytest_runtest_xxx() hooks.""" with catching_logs( self.caplog_handler, level=self.log_level, ) as caplog_handler, catching_logs( self.report_handler, level=self.log_level, ) as report_handler: caplog_handler.reset() report_handler.reset() item._store[caplog_records_key][when] = caplog_handler.records item._store[caplog_handler_key] = caplog_handler yield log = report_handler.stream.getvalue().strip() item.add_report_section(when, "log", log) @hookimpl(hookwrapper=True) def pytest_runtest_setup(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("setup") empty: Dict[str, List[logging.LogRecord]] = {} item._store[caplog_records_key] = empty yield from self._runtest_for(item, "setup") @hookimpl(hookwrapper=True) def pytest_runtest_call(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("call") yield from self._runtest_for(item, "call") @hookimpl(hookwrapper=True) def pytest_runtest_teardown(self, item: nodes.Item) -> Generator[None, None, None]: self.log_cli_handler.set_when("teardown") yield from self._runtest_for(item, "teardown") del item._store[caplog_records_key] del item._store[caplog_handler_key] @hookimpl def pytest_runtest_logfinish(self) -> None: self.log_cli_handler.set_when("finish") @hookimpl(hookwrapper=True, tryfirst=True) def pytest_sessionfinish(self) -> Generator[None, None, None]: self.log_cli_handler.set_when("sessionfinish") with catching_logs(self.log_cli_handler, level=self.log_cli_level): with catching_logs(self.log_file_handler, level=self.log_file_level): yield @hookimpl def pytest_unconfigure(self) -> None: # Close the FileHandler explicitly. # (logging.shutdown might have lost the weakref?!) self.log_file_handler.close() class _FileHandler(logging.FileHandler): """A logging FileHandler with pytest tweaks.""" def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingStreamHandler(logging.StreamHandler): """A logging StreamHandler used by the live logging feature: it will write a newline before the first log message in each test. During live logging we must also explicitly disable stdout/stderr capturing otherwise it will get captured and won't appear in the terminal. """ # Officially stream needs to be a IO[str], but TerminalReporter # isn't. So force it. stream: TerminalReporter = None # type: ignore def __init__( self, terminal_reporter: TerminalReporter, capture_manager: Optional[CaptureManager], ) -> None: logging.StreamHandler.__init__(self, stream=terminal_reporter) # type: ignore[arg-type] self.capture_manager = capture_manager self.reset() self.set_when(None) self._test_outcome_written = False def reset(self) -> None: """Reset the handler; should be called before the start of each test.""" self._first_record_emitted = False def set_when(self, when: Optional[str]) -> None: """Prepare for the given test phase (setup/call/teardown).""" self._when = when self._section_name_shown = False if when == "start": self._test_outcome_written = False def emit(self, record: logging.LogRecord) -> None: ctx_manager = ( self.capture_manager.global_and_fixture_disabled() if self.capture_manager else nullcontext() ) with ctx_manager: if not self._first_record_emitted: self.stream.write("\n") self._first_record_emitted = True elif self._when in ("teardown", "finish"): if not self._test_outcome_written: self._test_outcome_written = True self.stream.write("\n") if not self._section_name_shown and self._when: self.stream.section("live log " + self._when, sep="-", bold=True) self._section_name_shown = True super().emit(record) def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass class _LiveLoggingNullHandler(logging.NullHandler): """A logging handler used when live logging is disabled.""" def reset(self) -> None: pass def set_when(self, when: str) -> None: pass def handleError(self, record: logging.LogRecord) -> None: # Handled by LogCaptureHandler. pass
set_level
identifier_name
error.rs
// Copyright 2018 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::{fmt, env}; use hir::map::definitions::DefPathData; use mir; use ty::{self, Ty, layout}; use ty::layout::{Size, Align, LayoutError}; use rustc_target::spec::abi::Abi; use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef}; use backtrace::Backtrace; use ty::query::TyCtxtAt; use errors::DiagnosticBuilder; use syntax_pos::{Pos, Span}; use syntax::ast; use syntax::symbol::Symbol; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ErrorHandled { /// Already reported a lint or an error for this evaluation Reported, /// Don't emit an error, the evaluation failed because the MIR was generic /// and the substs didn't fully monomorphize it. TooGeneric, } impl ErrorHandled { pub fn assert_reported(self) { match self { ErrorHandled::Reported => {}, ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \ even though it was fully monomorphized"), } } } pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>; pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>; #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct ConstEvalErr<'tcx> { pub span: Span, pub error: ::mir::interpret::EvalErrorKind<'tcx, u64>, pub stacktrace: Vec<FrameInfo<'tcx>>, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct FrameInfo<'tcx> { pub call_site: Span, // this span is in the caller! pub instance: ty::Instance<'tcx>, pub lint_root: Option<ast::NodeId>, } impl<'tcx> fmt::Display for FrameInfo<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { if tcx.def_key(self.instance.def_id()).disambiguated_data.data == DefPathData::ClosureExpr { write!(f, "inside call to closure")?; } else { write!(f, "inside call to `{}`", self.instance)?; } if !self.call_site.is_dummy() { let lo = tcx.sess.source_map().lookup_char_pos_adj(self.call_site.lo()); write!(f, " at {}:{}:{}", lo.filename, lo.line, lo.col.to_usize() + 1)?; } Ok(()) }) } } impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> { pub fn struct_error(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> { self.struct_generic(tcx, message, None) } pub fn report_as_error(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str ) -> ErrorHandled { let err = self.struct_error(tcx, message); match err { Ok(mut err) => { err.emit(); ErrorHandled::Reported }, Err(err) => err, } } pub fn report_as_lint(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str, lint_root: ast::NodeId, ) -> ErrorHandled { let lint = self.struct_generic( tcx, message, Some(lint_root), ); match lint { Ok(mut lint) => { lint.emit(); ErrorHandled::Reported }, Err(err) => err, } } fn struct_generic( &self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str, lint_root: Option<ast::NodeId>, ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> { match self.error { EvalErrorKind::Layout(LayoutError::Unknown(_)) | EvalErrorKind::TooGeneric => return Err(ErrorHandled::TooGeneric), EvalErrorKind::Layout(LayoutError::SizeOverflow(_)) | EvalErrorKind::TypeckError => return Err(ErrorHandled::Reported), _ => {}, } trace!("reporting const eval failure at {:?}", self.span); let mut err = if let Some(lint_root) = lint_root { let node_id = self.stacktrace .iter() .rev() .filter_map(|frame| frame.lint_root) .next() .unwrap_or(lint_root); tcx.struct_span_lint_node( ::rustc::lint::builtin::CONST_ERR, node_id, tcx.span, message, ) } else { struct_error(tcx, message) }; err.span_label(self.span, self.error.to_string()); // Skip the last, which is just the environment of the constant. The stacktrace // is sometimes empty because we create "fake" eval contexts in CTFE to do work // on constant values. if self.stacktrace.len() > 0 { for frame_info in &self.stacktrace[..self.stacktrace.len()-1] { err.span_label(frame_info.call_site, frame_info.to_string()); } } Ok(err) } } pub fn struct_error<'a, 'gcx, 'tcx>( tcx: TyCtxtAt<'a, 'gcx, 'tcx>, msg: &str, ) -> DiagnosticBuilder<'tcx> { struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg) } #[derive(Debug, Clone)] pub struct EvalError<'tcx> { pub kind: EvalErrorKind<'tcx, u64>, pub backtrace: Option<Box<Backtrace>>, } impl<'tcx> EvalError<'tcx> { pub fn print_backtrace(&mut self) { if let Some(ref mut backtrace) = self.backtrace { print_backtrace(&mut *backtrace); } } } fn print_backtrace(backtrace: &mut Backtrace) { backtrace.resolve(); eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace); } impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> { fn from(kind: EvalErrorKind<'tcx, u64>) -> Self { let backtrace = match env::var("RUST_CTFE_BACKTRACE") { // matching RUST_BACKTRACE, we treat "0" the same as "not present". Ok(ref val) if val != "0" => { let mut backtrace = Backtrace::new_unresolved(); if val == "immediate" { // Print it now print_backtrace(&mut backtrace); None } else { Some(Box::new(backtrace)) } }, _ => None, }; EvalError { kind, backtrace, } } } pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>; #[derive(Clone, RustcEncodable, RustcDecodable)] pub enum EvalErrorKind<'tcx, O> { /// This variant is used by machines to signal their own errors that do not /// match an existing variant MachineError(String), FunctionAbiMismatch(Abi, Abi), FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>), FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>), FunctionArgCountMismatch, NoMirFor(String), UnterminatedCString(Pointer), DanglingPointerDeref, DoubleFree, InvalidMemoryAccess, InvalidFunctionPointer, InvalidBool, InvalidDiscriminant(ScalarMaybeUndef), PointerOutOfBounds { ptr: Pointer, check: InboundsCheck, allocation_size: Size, }, InvalidNullPointerUsage, ReadPointerAsBytes, ReadBytesAsPointer, ReadForeignStatic, InvalidPointerMath, ReadUndefBytes(Size), DeadLocal, InvalidBoolOp(mir::BinOp), Unimplemented(String), DerefFunctionPointer, ExecuteMemory, BoundsCheck { len: O, index: O }, Overflow(mir::BinOp), OverflowNeg, DivisionByZero, RemainderByZero, Intrinsic(String), InvalidChar(u128), StackFrameLimitReached, OutOfTls, TlsOutOfBounds, AbiViolation(String), AlignmentCheckFailed { required: Align, has: Align, }, ValidationFailure(String), CalledClosureAsFunction, VtableForArgumentlessMethod, ModifiedConstantMemory, ModifiedStatic, AssumptionNotHeld, InlineAsm, TypeNotPrimitive(Ty<'tcx>), ReallocatedWrongMemoryKind(String, String), DeallocatedWrongMemoryKind(String, String), ReallocateNonBasePtr, DeallocateNonBasePtr, IncorrectAllocationInformation(Size, Size, Align, Align), Layout(layout::LayoutError<'tcx>), HeapAllocZeroBytes, HeapAllocNonPowerOfTwoAlignment(u64), Unreachable, Panic { msg: Symbol, line: u32, col: u32, file: Symbol, }, ReadFromReturnPointer, PathNotFound(Vec<String>), UnimplementedTraitSelection, /// Abort in case type errors are reached TypeckError, /// Resolution can fail if we are in a too generic context TooGeneric, /// Cannot compute this constant because it depends on another one /// which already produced an error ReferencedConstant, GeneratorResumedAfterReturn, GeneratorResumedAfterPanic, InfiniteLoop, } pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>; impl<'tcx, O> EvalErrorKind<'tcx, O> { pub fn description(&self) -> &str
} impl<'tcx> fmt::Display for EvalError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.kind) } } impl<'tcx> fmt::Display for EvalErrorKind<'tcx, u64> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } impl<'tcx, O: fmt::Debug> fmt::Debug for EvalErrorKind<'tcx, O> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::EvalErrorKind::*; match *self { PointerOutOfBounds { ptr, check, allocation_size } => { write!(f, "Pointer must be in-bounds{} at offset {}, but is outside bounds of \ allocation {} which has size {}", match check { InboundsCheck::Live => " and live", InboundsCheck::MaybeDead => "", }, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes()) }, ValidationFailure(ref err) => { write!(f, "type validation failed: {}", err) } NoMirFor(ref func) => write!(f, "no mir for `{}`", func), FunctionAbiMismatch(caller_abi, callee_abi) => write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}", callee_abi, caller_abi), FunctionArgMismatch(caller_ty, callee_ty) => write!(f, "tried to call a function with argument of type {:?} \ passing data of type {:?}", callee_ty, caller_ty), FunctionRetMismatch(caller_ty, callee_ty) => write!(f, "tried to call a function with return type {:?} \ passing return place of type {:?}", callee_ty, caller_ty), FunctionArgCountMismatch => write!(f, "tried to call a function with incorrect number of arguments"), BoundsCheck { ref len, ref index } => write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index), ReallocatedWrongMemoryKind(ref old, ref new) => write!(f, "tried to reallocate memory from {} to {}", old, new), DeallocatedWrongMemoryKind(ref old, ref new) => write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new), Intrinsic(ref err) => write!(f, "{}", err), InvalidChar(c) => write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c), AlignmentCheckFailed { required, has } => write!(f, "tried to access memory with alignment {}, but alignment {} is required", has.bytes(), required.bytes()), TypeNotPrimitive(ty) => write!(f, "expected primitive type, got {}", ty), Layout(ref err) => write!(f, "rustc layout computation failed: {:?}", err), PathNotFound(ref path) => write!(f, "Cannot find path {:?}", path), MachineError(ref inner) => write!(f, "{}", inner), IncorrectAllocationInformation(size, size2, align, align2) => write!(f, "incorrect alloc info: expected size {} and align {}, \ got size {} and align {}", size.bytes(), align.bytes(), size2.bytes(), align2.bytes()), Panic { ref msg, line, col, ref file } => write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col), InvalidDiscriminant(val) => write!(f, "encountered invalid enum discriminant {}", val), _ => write!(f, "{}", self.description()), } } }
{ use self::EvalErrorKind::*; match *self { MachineError(ref inner) => inner, FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..) | FunctionArgCountMismatch => "tried to call a function through a function pointer of incompatible type", InvalidMemoryAccess => "tried to access memory through an invalid pointer", DanglingPointerDeref => "dangling pointer was dereferenced", DoubleFree => "tried to deallocate dangling pointer", InvalidFunctionPointer => "tried to use a function pointer after offsetting it", InvalidBool => "invalid boolean value read", InvalidDiscriminant(..) => "invalid enum discriminant value read", PointerOutOfBounds { .. } => "pointer offset outside bounds of allocation", InvalidNullPointerUsage => "invalid use of NULL pointer", ValidationFailure(..) => "type validation failed", ReadPointerAsBytes => "a raw memory access tried to access part of a pointer value as raw bytes", ReadBytesAsPointer => "a memory access tried to interpret some bytes as a pointer", ReadForeignStatic => "tried to read from foreign (extern) static", InvalidPointerMath => "attempted to do invalid arithmetic on pointers that would leak base addresses, \ e.g., comparing pointers into different allocations", ReadUndefBytes(_) => "attempted to read undefined bytes", DeadLocal => "tried to access a dead local variable", InvalidBoolOp(_) => "invalid boolean operation", Unimplemented(ref msg) => msg, DerefFunctionPointer => "tried to dereference a function pointer", ExecuteMemory => "tried to treat a memory pointer as a function pointer", BoundsCheck{..} => "array index out of bounds", Intrinsic(..) => "intrinsic failed", NoMirFor(..) => "mir not found", InvalidChar(..) => "tried to interpret an invalid 32-bit value as a char", StackFrameLimitReached => "reached the configured maximum number of stack frames", OutOfTls => "reached the maximum number of representable TLS keys", TlsOutOfBounds => "accessed an invalid (unallocated) TLS key", AbiViolation(ref msg) => msg, AlignmentCheckFailed{..} => "tried to execute a misaligned read or write", CalledClosureAsFunction => "tried to call a closure through a function pointer", VtableForArgumentlessMethod => "tried to call a vtable function without arguments", ModifiedConstantMemory => "tried to modify constant memory", ModifiedStatic => "tried to modify a static's initial value from another static's initializer", AssumptionNotHeld => "`assume` argument was false", InlineAsm => "miri does not support inline assembly", TypeNotPrimitive(_) => "expected primitive type, got nonprimitive", ReallocatedWrongMemoryKind(_, _) => "tried to reallocate memory from one kind to another", DeallocatedWrongMemoryKind(_, _) => "tried to deallocate memory of the wrong kind", ReallocateNonBasePtr => "tried to reallocate with a pointer not to the beginning of an existing object", DeallocateNonBasePtr => "tried to deallocate with a pointer not to the beginning of an existing object", IncorrectAllocationInformation(..) => "tried to deallocate or reallocate using incorrect alignment or size", Layout(_) => "rustc layout computation failed", UnterminatedCString(_) => "attempted to get length of a null terminated string, but no null found before end \ of allocation", HeapAllocZeroBytes => "tried to re-, de- or allocate zero bytes on the heap", HeapAllocNonPowerOfTwoAlignment(_) => "tried to re-, de-, or allocate heap memory with alignment that is not a power of \ two", Unreachable => "entered unreachable code", Panic { .. } => "the evaluated program panicked", ReadFromReturnPointer => "tried to read from the return pointer", PathNotFound(_) => "a path could not be resolved, maybe the crate is not loaded", UnimplementedTraitSelection => "there were unresolved type arguments during trait selection", TypeckError => "encountered constants with type errors, stopping evaluation", TooGeneric => "encountered overly generic constant", ReferencedConstant => "referenced constant has errors", Overflow(mir::BinOp::Add) => "attempt to add with overflow", Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow", Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow", Overflow(mir::BinOp::Div) => "attempt to divide with overflow", Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow", OverflowNeg => "attempt to negate with overflow", Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow", Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow", Overflow(op) => bug!("{:?} cannot overflow", op), DivisionByZero => "attempt to divide by zero", RemainderByZero => "attempt to calculate the remainder with a divisor of zero", GeneratorResumedAfterReturn => "generator resumed after completion", GeneratorResumedAfterPanic => "generator resumed after panicking", InfiniteLoop => "duplicate interpreter state observed here, const evaluation will never terminate", } }
identifier_body
error.rs
// Copyright 2018 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::{fmt, env}; use hir::map::definitions::DefPathData; use mir; use ty::{self, Ty, layout}; use ty::layout::{Size, Align, LayoutError}; use rustc_target::spec::abi::Abi; use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef}; use backtrace::Backtrace; use ty::query::TyCtxtAt; use errors::DiagnosticBuilder; use syntax_pos::{Pos, Span}; use syntax::ast; use syntax::symbol::Symbol; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ErrorHandled { /// Already reported a lint or an error for this evaluation Reported, /// Don't emit an error, the evaluation failed because the MIR was generic /// and the substs didn't fully monomorphize it. TooGeneric, } impl ErrorHandled { pub fn assert_reported(self) { match self { ErrorHandled::Reported => {}, ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \ even though it was fully monomorphized"), } } } pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>; pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>; #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct ConstEvalErr<'tcx> { pub span: Span, pub error: ::mir::interpret::EvalErrorKind<'tcx, u64>, pub stacktrace: Vec<FrameInfo<'tcx>>, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct FrameInfo<'tcx> { pub call_site: Span, // this span is in the caller! pub instance: ty::Instance<'tcx>, pub lint_root: Option<ast::NodeId>, } impl<'tcx> fmt::Display for FrameInfo<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { if tcx.def_key(self.instance.def_id()).disambiguated_data.data == DefPathData::ClosureExpr { write!(f, "inside call to closure")?; } else { write!(f, "inside call to `{}`", self.instance)?; } if !self.call_site.is_dummy() { let lo = tcx.sess.source_map().lookup_char_pos_adj(self.call_site.lo()); write!(f, " at {}:{}:{}", lo.filename, lo.line, lo.col.to_usize() + 1)?; } Ok(()) }) } } impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> { pub fn struct_error(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> { self.struct_generic(tcx, message, None) } pub fn report_as_error(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str ) -> ErrorHandled { let err = self.struct_error(tcx, message); match err { Ok(mut err) => { err.emit(); ErrorHandled::Reported }, Err(err) => err, } } pub fn report_as_lint(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str, lint_root: ast::NodeId, ) -> ErrorHandled { let lint = self.struct_generic( tcx, message, Some(lint_root), ); match lint { Ok(mut lint) => { lint.emit(); ErrorHandled::Reported }, Err(err) => err, } } fn struct_generic( &self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str, lint_root: Option<ast::NodeId>, ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> { match self.error { EvalErrorKind::Layout(LayoutError::Unknown(_)) | EvalErrorKind::TooGeneric => return Err(ErrorHandled::TooGeneric), EvalErrorKind::Layout(LayoutError::SizeOverflow(_)) | EvalErrorKind::TypeckError => return Err(ErrorHandled::Reported), _ => {}, } trace!("reporting const eval failure at {:?}", self.span); let mut err = if let Some(lint_root) = lint_root { let node_id = self.stacktrace .iter() .rev() .filter_map(|frame| frame.lint_root) .next() .unwrap_or(lint_root); tcx.struct_span_lint_node( ::rustc::lint::builtin::CONST_ERR, node_id, tcx.span, message, ) } else { struct_error(tcx, message) }; err.span_label(self.span, self.error.to_string()); // Skip the last, which is just the environment of the constant. The stacktrace // is sometimes empty because we create "fake" eval contexts in CTFE to do work // on constant values. if self.stacktrace.len() > 0 { for frame_info in &self.stacktrace[..self.stacktrace.len()-1] { err.span_label(frame_info.call_site, frame_info.to_string()); } } Ok(err) } } pub fn struct_error<'a, 'gcx, 'tcx>( tcx: TyCtxtAt<'a, 'gcx, 'tcx>, msg: &str, ) -> DiagnosticBuilder<'tcx> { struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg) } #[derive(Debug, Clone)] pub struct EvalError<'tcx> { pub kind: EvalErrorKind<'tcx, u64>, pub backtrace: Option<Box<Backtrace>>, } impl<'tcx> EvalError<'tcx> { pub fn print_backtrace(&mut self) { if let Some(ref mut backtrace) = self.backtrace { print_backtrace(&mut *backtrace); } } } fn print_backtrace(backtrace: &mut Backtrace) { backtrace.resolve(); eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace); } impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> { fn from(kind: EvalErrorKind<'tcx, u64>) -> Self { let backtrace = match env::var("RUST_CTFE_BACKTRACE") { // matching RUST_BACKTRACE, we treat "0" the same as "not present". Ok(ref val) if val != "0" => { let mut backtrace = Backtrace::new_unresolved(); if val == "immediate" { // Print it now print_backtrace(&mut backtrace); None } else { Some(Box::new(backtrace)) } }, _ => None, }; EvalError { kind, backtrace, } } } pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>; #[derive(Clone, RustcEncodable, RustcDecodable)] pub enum EvalErrorKind<'tcx, O> { /// This variant is used by machines to signal their own errors that do not /// match an existing variant MachineError(String), FunctionAbiMismatch(Abi, Abi), FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>), FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>), FunctionArgCountMismatch, NoMirFor(String), UnterminatedCString(Pointer), DanglingPointerDeref, DoubleFree, InvalidMemoryAccess, InvalidFunctionPointer, InvalidBool, InvalidDiscriminant(ScalarMaybeUndef), PointerOutOfBounds { ptr: Pointer, check: InboundsCheck, allocation_size: Size, }, InvalidNullPointerUsage, ReadPointerAsBytes, ReadBytesAsPointer, ReadForeignStatic, InvalidPointerMath, ReadUndefBytes(Size), DeadLocal, InvalidBoolOp(mir::BinOp), Unimplemented(String), DerefFunctionPointer, ExecuteMemory, BoundsCheck { len: O, index: O }, Overflow(mir::BinOp), OverflowNeg, DivisionByZero, RemainderByZero, Intrinsic(String), InvalidChar(u128), StackFrameLimitReached, OutOfTls, TlsOutOfBounds, AbiViolation(String), AlignmentCheckFailed { required: Align, has: Align, }, ValidationFailure(String), CalledClosureAsFunction, VtableForArgumentlessMethod, ModifiedConstantMemory, ModifiedStatic, AssumptionNotHeld, InlineAsm, TypeNotPrimitive(Ty<'tcx>), ReallocatedWrongMemoryKind(String, String), DeallocatedWrongMemoryKind(String, String), ReallocateNonBasePtr, DeallocateNonBasePtr, IncorrectAllocationInformation(Size, Size, Align, Align), Layout(layout::LayoutError<'tcx>), HeapAllocZeroBytes, HeapAllocNonPowerOfTwoAlignment(u64), Unreachable, Panic { msg: Symbol, line: u32, col: u32, file: Symbol, }, ReadFromReturnPointer, PathNotFound(Vec<String>), UnimplementedTraitSelection, /// Abort in case type errors are reached TypeckError, /// Resolution can fail if we are in a too generic context TooGeneric, /// Cannot compute this constant because it depends on another one /// which already produced an error ReferencedConstant, GeneratorResumedAfterReturn, GeneratorResumedAfterPanic, InfiniteLoop, } pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>; impl<'tcx, O> EvalErrorKind<'tcx, O> { pub fn description(&self) -> &str { use self::EvalErrorKind::*; match *self { MachineError(ref inner) => inner, FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..) | FunctionArgCountMismatch => "tried to call a function through a function pointer of incompatible type", InvalidMemoryAccess => "tried to access memory through an invalid pointer", DanglingPointerDeref => "dangling pointer was dereferenced", DoubleFree => "tried to deallocate dangling pointer", InvalidFunctionPointer => "tried to use a function pointer after offsetting it", InvalidBool => "invalid boolean value read", InvalidDiscriminant(..) => "invalid enum discriminant value read", PointerOutOfBounds { .. } => "pointer offset outside bounds of allocation", InvalidNullPointerUsage => "invalid use of NULL pointer", ValidationFailure(..) => "type validation failed", ReadPointerAsBytes => "a raw memory access tried to access part of a pointer value as raw bytes", ReadBytesAsPointer => "a memory access tried to interpret some bytes as a pointer", ReadForeignStatic => "tried to read from foreign (extern) static", InvalidPointerMath => "attempted to do invalid arithmetic on pointers that would leak base addresses, \ e.g., comparing pointers into different allocations", ReadUndefBytes(_) => "attempted to read undefined bytes", DeadLocal => "tried to access a dead local variable", InvalidBoolOp(_) => "invalid boolean operation", Unimplemented(ref msg) => msg, DerefFunctionPointer => "tried to dereference a function pointer", ExecuteMemory => "tried to treat a memory pointer as a function pointer", BoundsCheck{..} => "array index out of bounds", Intrinsic(..) => "intrinsic failed", NoMirFor(..) => "mir not found", InvalidChar(..) => "tried to interpret an invalid 32-bit value as a char", StackFrameLimitReached => "reached the configured maximum number of stack frames", OutOfTls => "reached the maximum number of representable TLS keys", TlsOutOfBounds => "accessed an invalid (unallocated) TLS key", AbiViolation(ref msg) => msg, AlignmentCheckFailed{..} => "tried to execute a misaligned read or write", CalledClosureAsFunction => "tried to call a closure through a function pointer", VtableForArgumentlessMethod => "tried to call a vtable function without arguments", ModifiedConstantMemory => "tried to modify constant memory", ModifiedStatic => "tried to modify a static's initial value from another static's initializer", AssumptionNotHeld => "`assume` argument was false", InlineAsm => "miri does not support inline assembly", TypeNotPrimitive(_) => "expected primitive type, got nonprimitive", ReallocatedWrongMemoryKind(_, _) => "tried to reallocate memory from one kind to another", DeallocatedWrongMemoryKind(_, _) => "tried to deallocate memory of the wrong kind", ReallocateNonBasePtr => "tried to reallocate with a pointer not to the beginning of an existing object", DeallocateNonBasePtr => "tried to deallocate with a pointer not to the beginning of an existing object", IncorrectAllocationInformation(..) => "tried to deallocate or reallocate using incorrect alignment or size", Layout(_) => "rustc layout computation failed", UnterminatedCString(_) => "attempted to get length of a null terminated string, but no null found before end \ of allocation", HeapAllocZeroBytes => "tried to re-, de- or allocate zero bytes on the heap", HeapAllocNonPowerOfTwoAlignment(_) => "tried to re-, de-, or allocate heap memory with alignment that is not a power of \ two", Unreachable => "entered unreachable code", Panic { .. } => "the evaluated program panicked", ReadFromReturnPointer => "tried to read from the return pointer", PathNotFound(_) => "a path could not be resolved, maybe the crate is not loaded", UnimplementedTraitSelection => "there were unresolved type arguments during trait selection", TypeckError => "encountered constants with type errors, stopping evaluation", TooGeneric => "encountered overly generic constant", ReferencedConstant => "referenced constant has errors", Overflow(mir::BinOp::Add) => "attempt to add with overflow", Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow", Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow", Overflow(mir::BinOp::Div) => "attempt to divide with overflow", Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow", OverflowNeg => "attempt to negate with overflow", Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow", Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow", Overflow(op) => bug!("{:?} cannot overflow", op), DivisionByZero => "attempt to divide by zero", RemainderByZero => "attempt to calculate the remainder with a divisor of zero", GeneratorResumedAfterReturn => "generator resumed after completion", GeneratorResumedAfterPanic => "generator resumed after panicking", InfiniteLoop => "duplicate interpreter state observed here, const evaluation will never terminate", } } } impl<'tcx> fmt::Display for EvalError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.kind) } } impl<'tcx> fmt::Display for EvalErrorKind<'tcx, u64> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } impl<'tcx, O: fmt::Debug> fmt::Debug for EvalErrorKind<'tcx, O> { fn
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::EvalErrorKind::*; match *self { PointerOutOfBounds { ptr, check, allocation_size } => { write!(f, "Pointer must be in-bounds{} at offset {}, but is outside bounds of \ allocation {} which has size {}", match check { InboundsCheck::Live => " and live", InboundsCheck::MaybeDead => "", }, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes()) }, ValidationFailure(ref err) => { write!(f, "type validation failed: {}", err) } NoMirFor(ref func) => write!(f, "no mir for `{}`", func), FunctionAbiMismatch(caller_abi, callee_abi) => write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}", callee_abi, caller_abi), FunctionArgMismatch(caller_ty, callee_ty) => write!(f, "tried to call a function with argument of type {:?} \ passing data of type {:?}", callee_ty, caller_ty), FunctionRetMismatch(caller_ty, callee_ty) => write!(f, "tried to call a function with return type {:?} \ passing return place of type {:?}", callee_ty, caller_ty), FunctionArgCountMismatch => write!(f, "tried to call a function with incorrect number of arguments"), BoundsCheck { ref len, ref index } => write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index), ReallocatedWrongMemoryKind(ref old, ref new) => write!(f, "tried to reallocate memory from {} to {}", old, new), DeallocatedWrongMemoryKind(ref old, ref new) => write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new), Intrinsic(ref err) => write!(f, "{}", err), InvalidChar(c) => write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c), AlignmentCheckFailed { required, has } => write!(f, "tried to access memory with alignment {}, but alignment {} is required", has.bytes(), required.bytes()), TypeNotPrimitive(ty) => write!(f, "expected primitive type, got {}", ty), Layout(ref err) => write!(f, "rustc layout computation failed: {:?}", err), PathNotFound(ref path) => write!(f, "Cannot find path {:?}", path), MachineError(ref inner) => write!(f, "{}", inner), IncorrectAllocationInformation(size, size2, align, align2) => write!(f, "incorrect alloc info: expected size {} and align {}, \ got size {} and align {}", size.bytes(), align.bytes(), size2.bytes(), align2.bytes()), Panic { ref msg, line, col, ref file } => write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col), InvalidDiscriminant(val) => write!(f, "encountered invalid enum discriminant {}", val), _ => write!(f, "{}", self.description()), } } }
fmt
identifier_name
error.rs
// Copyright 2018 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::{fmt, env}; use hir::map::definitions::DefPathData; use mir; use ty::{self, Ty, layout}; use ty::layout::{Size, Align, LayoutError}; use rustc_target::spec::abi::Abi; use super::{RawConst, Pointer, InboundsCheck, ScalarMaybeUndef}; use backtrace::Backtrace; use ty::query::TyCtxtAt; use errors::DiagnosticBuilder; use syntax_pos::{Pos, Span}; use syntax::ast; use syntax::symbol::Symbol; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum ErrorHandled { /// Already reported a lint or an error for this evaluation Reported, /// Don't emit an error, the evaluation failed because the MIR was generic /// and the substs didn't fully monomorphize it. TooGeneric, } impl ErrorHandled { pub fn assert_reported(self) { match self { ErrorHandled::Reported => {}, ErrorHandled::TooGeneric => bug!("MIR interpretation failed without reporting an error \ even though it was fully monomorphized"), } } } pub type ConstEvalRawResult<'tcx> = Result<RawConst<'tcx>, ErrorHandled>; pub type ConstEvalResult<'tcx> = Result<&'tcx ty::Const<'tcx>, ErrorHandled>; #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct ConstEvalErr<'tcx> { pub span: Span, pub error: ::mir::interpret::EvalErrorKind<'tcx, u64>, pub stacktrace: Vec<FrameInfo<'tcx>>, } #[derive(Clone, Debug, RustcEncodable, RustcDecodable)] pub struct FrameInfo<'tcx> { pub call_site: Span, // this span is in the caller! pub instance: ty::Instance<'tcx>, pub lint_root: Option<ast::NodeId>, } impl<'tcx> fmt::Display for FrameInfo<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { ty::tls::with(|tcx| { if tcx.def_key(self.instance.def_id()).disambiguated_data.data == DefPathData::ClosureExpr { write!(f, "inside call to closure")?; } else { write!(f, "inside call to `{}`", self.instance)?; } if !self.call_site.is_dummy() { let lo = tcx.sess.source_map().lookup_char_pos_adj(self.call_site.lo()); write!(f, " at {}:{}:{}", lo.filename, lo.line, lo.col.to_usize() + 1)?; } Ok(()) }) } } impl<'a, 'gcx, 'tcx> ConstEvalErr<'tcx> { pub fn struct_error(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> { self.struct_generic(tcx, message, None) } pub fn report_as_error(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str ) -> ErrorHandled { let err = self.struct_error(tcx, message); match err { Ok(mut err) => { err.emit(); ErrorHandled::Reported }, Err(err) => err, } } pub fn report_as_lint(&self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str, lint_root: ast::NodeId, ) -> ErrorHandled { let lint = self.struct_generic( tcx, message, Some(lint_root), ); match lint { Ok(mut lint) => { lint.emit(); ErrorHandled::Reported }, Err(err) => err, } } fn struct_generic( &self, tcx: TyCtxtAt<'a, 'gcx, 'tcx>, message: &str, lint_root: Option<ast::NodeId>, ) -> Result<DiagnosticBuilder<'tcx>, ErrorHandled> { match self.error { EvalErrorKind::Layout(LayoutError::Unknown(_)) | EvalErrorKind::TooGeneric => return Err(ErrorHandled::TooGeneric), EvalErrorKind::Layout(LayoutError::SizeOverflow(_)) | EvalErrorKind::TypeckError => return Err(ErrorHandled::Reported), _ => {}, } trace!("reporting const eval failure at {:?}", self.span); let mut err = if let Some(lint_root) = lint_root { let node_id = self.stacktrace .iter() .rev() .filter_map(|frame| frame.lint_root) .next() .unwrap_or(lint_root); tcx.struct_span_lint_node( ::rustc::lint::builtin::CONST_ERR, node_id, tcx.span, message, ) } else { struct_error(tcx, message) }; err.span_label(self.span, self.error.to_string()); // Skip the last, which is just the environment of the constant. The stacktrace // is sometimes empty because we create "fake" eval contexts in CTFE to do work // on constant values. if self.stacktrace.len() > 0 { for frame_info in &self.stacktrace[..self.stacktrace.len()-1] { err.span_label(frame_info.call_site, frame_info.to_string()); } } Ok(err) } } pub fn struct_error<'a, 'gcx, 'tcx>( tcx: TyCtxtAt<'a, 'gcx, 'tcx>, msg: &str, ) -> DiagnosticBuilder<'tcx> { struct_span_err!(tcx.sess, tcx.span, E0080, "{}", msg) } #[derive(Debug, Clone)] pub struct EvalError<'tcx> { pub kind: EvalErrorKind<'tcx, u64>, pub backtrace: Option<Box<Backtrace>>, } impl<'tcx> EvalError<'tcx> { pub fn print_backtrace(&mut self) { if let Some(ref mut backtrace) = self.backtrace { print_backtrace(&mut *backtrace); } } } fn print_backtrace(backtrace: &mut Backtrace) { backtrace.resolve(); eprintln!("\n\nAn error occurred in miri:\n{:?}", backtrace); } impl<'tcx> From<EvalErrorKind<'tcx, u64>> for EvalError<'tcx> { fn from(kind: EvalErrorKind<'tcx, u64>) -> Self { let backtrace = match env::var("RUST_CTFE_BACKTRACE") { // matching RUST_BACKTRACE, we treat "0" the same as "not present". Ok(ref val) if val != "0" => { let mut backtrace = Backtrace::new_unresolved(); if val == "immediate" { // Print it now print_backtrace(&mut backtrace); None } else { Some(Box::new(backtrace)) } }, _ => None, }; EvalError { kind, backtrace, } } } pub type AssertMessage<'tcx> = EvalErrorKind<'tcx, mir::Operand<'tcx>>; #[derive(Clone, RustcEncodable, RustcDecodable)] pub enum EvalErrorKind<'tcx, O> { /// This variant is used by machines to signal their own errors that do not /// match an existing variant MachineError(String), FunctionAbiMismatch(Abi, Abi), FunctionArgMismatch(Ty<'tcx>, Ty<'tcx>), FunctionRetMismatch(Ty<'tcx>, Ty<'tcx>), FunctionArgCountMismatch, NoMirFor(String), UnterminatedCString(Pointer), DanglingPointerDeref, DoubleFree, InvalidMemoryAccess, InvalidFunctionPointer, InvalidBool, InvalidDiscriminant(ScalarMaybeUndef), PointerOutOfBounds { ptr: Pointer, check: InboundsCheck, allocation_size: Size, }, InvalidNullPointerUsage, ReadPointerAsBytes, ReadBytesAsPointer, ReadForeignStatic, InvalidPointerMath, ReadUndefBytes(Size), DeadLocal, InvalidBoolOp(mir::BinOp), Unimplemented(String), DerefFunctionPointer, ExecuteMemory, BoundsCheck { len: O, index: O }, Overflow(mir::BinOp), OverflowNeg, DivisionByZero, RemainderByZero, Intrinsic(String), InvalidChar(u128), StackFrameLimitReached, OutOfTls, TlsOutOfBounds, AbiViolation(String), AlignmentCheckFailed { required: Align, has: Align, }, ValidationFailure(String), CalledClosureAsFunction, VtableForArgumentlessMethod, ModifiedConstantMemory, ModifiedStatic, AssumptionNotHeld, InlineAsm, TypeNotPrimitive(Ty<'tcx>), ReallocatedWrongMemoryKind(String, String), DeallocatedWrongMemoryKind(String, String), ReallocateNonBasePtr, DeallocateNonBasePtr, IncorrectAllocationInformation(Size, Size, Align, Align), Layout(layout::LayoutError<'tcx>), HeapAllocZeroBytes, HeapAllocNonPowerOfTwoAlignment(u64), Unreachable, Panic { msg: Symbol, line: u32, col: u32, file: Symbol, }, ReadFromReturnPointer, PathNotFound(Vec<String>), UnimplementedTraitSelection, /// Abort in case type errors are reached TypeckError, /// Resolution can fail if we are in a too generic context TooGeneric, /// Cannot compute this constant because it depends on another one /// which already produced an error ReferencedConstant, GeneratorResumedAfterReturn, GeneratorResumedAfterPanic, InfiniteLoop, } pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>; impl<'tcx, O> EvalErrorKind<'tcx, O> { pub fn description(&self) -> &str { use self::EvalErrorKind::*; match *self { MachineError(ref inner) => inner, FunctionAbiMismatch(..) | FunctionArgMismatch(..) | FunctionRetMismatch(..) | FunctionArgCountMismatch => "tried to call a function through a function pointer of incompatible type", InvalidMemoryAccess => "tried to access memory through an invalid pointer", DanglingPointerDeref => "dangling pointer was dereferenced", DoubleFree => "tried to deallocate dangling pointer", InvalidFunctionPointer => "tried to use a function pointer after offsetting it", InvalidBool => "invalid boolean value read", InvalidDiscriminant(..) => "invalid enum discriminant value read", PointerOutOfBounds { .. } => "pointer offset outside bounds of allocation", InvalidNullPointerUsage => "invalid use of NULL pointer", ValidationFailure(..) => "type validation failed", ReadPointerAsBytes => "a raw memory access tried to access part of a pointer value as raw bytes",
"tried to read from foreign (extern) static", InvalidPointerMath => "attempted to do invalid arithmetic on pointers that would leak base addresses, \ e.g., comparing pointers into different allocations", ReadUndefBytes(_) => "attempted to read undefined bytes", DeadLocal => "tried to access a dead local variable", InvalidBoolOp(_) => "invalid boolean operation", Unimplemented(ref msg) => msg, DerefFunctionPointer => "tried to dereference a function pointer", ExecuteMemory => "tried to treat a memory pointer as a function pointer", BoundsCheck{..} => "array index out of bounds", Intrinsic(..) => "intrinsic failed", NoMirFor(..) => "mir not found", InvalidChar(..) => "tried to interpret an invalid 32-bit value as a char", StackFrameLimitReached => "reached the configured maximum number of stack frames", OutOfTls => "reached the maximum number of representable TLS keys", TlsOutOfBounds => "accessed an invalid (unallocated) TLS key", AbiViolation(ref msg) => msg, AlignmentCheckFailed{..} => "tried to execute a misaligned read or write", CalledClosureAsFunction => "tried to call a closure through a function pointer", VtableForArgumentlessMethod => "tried to call a vtable function without arguments", ModifiedConstantMemory => "tried to modify constant memory", ModifiedStatic => "tried to modify a static's initial value from another static's initializer", AssumptionNotHeld => "`assume` argument was false", InlineAsm => "miri does not support inline assembly", TypeNotPrimitive(_) => "expected primitive type, got nonprimitive", ReallocatedWrongMemoryKind(_, _) => "tried to reallocate memory from one kind to another", DeallocatedWrongMemoryKind(_, _) => "tried to deallocate memory of the wrong kind", ReallocateNonBasePtr => "tried to reallocate with a pointer not to the beginning of an existing object", DeallocateNonBasePtr => "tried to deallocate with a pointer not to the beginning of an existing object", IncorrectAllocationInformation(..) => "tried to deallocate or reallocate using incorrect alignment or size", Layout(_) => "rustc layout computation failed", UnterminatedCString(_) => "attempted to get length of a null terminated string, but no null found before end \ of allocation", HeapAllocZeroBytes => "tried to re-, de- or allocate zero bytes on the heap", HeapAllocNonPowerOfTwoAlignment(_) => "tried to re-, de-, or allocate heap memory with alignment that is not a power of \ two", Unreachable => "entered unreachable code", Panic { .. } => "the evaluated program panicked", ReadFromReturnPointer => "tried to read from the return pointer", PathNotFound(_) => "a path could not be resolved, maybe the crate is not loaded", UnimplementedTraitSelection => "there were unresolved type arguments during trait selection", TypeckError => "encountered constants with type errors, stopping evaluation", TooGeneric => "encountered overly generic constant", ReferencedConstant => "referenced constant has errors", Overflow(mir::BinOp::Add) => "attempt to add with overflow", Overflow(mir::BinOp::Sub) => "attempt to subtract with overflow", Overflow(mir::BinOp::Mul) => "attempt to multiply with overflow", Overflow(mir::BinOp::Div) => "attempt to divide with overflow", Overflow(mir::BinOp::Rem) => "attempt to calculate the remainder with overflow", OverflowNeg => "attempt to negate with overflow", Overflow(mir::BinOp::Shr) => "attempt to shift right with overflow", Overflow(mir::BinOp::Shl) => "attempt to shift left with overflow", Overflow(op) => bug!("{:?} cannot overflow", op), DivisionByZero => "attempt to divide by zero", RemainderByZero => "attempt to calculate the remainder with a divisor of zero", GeneratorResumedAfterReturn => "generator resumed after completion", GeneratorResumedAfterPanic => "generator resumed after panicking", InfiniteLoop => "duplicate interpreter state observed here, const evaluation will never terminate", } } } impl<'tcx> fmt::Display for EvalError<'tcx> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.kind) } } impl<'tcx> fmt::Display for EvalErrorKind<'tcx, u64> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self) } } impl<'tcx, O: fmt::Debug> fmt::Debug for EvalErrorKind<'tcx, O> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use self::EvalErrorKind::*; match *self { PointerOutOfBounds { ptr, check, allocation_size } => { write!(f, "Pointer must be in-bounds{} at offset {}, but is outside bounds of \ allocation {} which has size {}", match check { InboundsCheck::Live => " and live", InboundsCheck::MaybeDead => "", }, ptr.offset.bytes(), ptr.alloc_id, allocation_size.bytes()) }, ValidationFailure(ref err) => { write!(f, "type validation failed: {}", err) } NoMirFor(ref func) => write!(f, "no mir for `{}`", func), FunctionAbiMismatch(caller_abi, callee_abi) => write!(f, "tried to call a function with ABI {:?} using caller ABI {:?}", callee_abi, caller_abi), FunctionArgMismatch(caller_ty, callee_ty) => write!(f, "tried to call a function with argument of type {:?} \ passing data of type {:?}", callee_ty, caller_ty), FunctionRetMismatch(caller_ty, callee_ty) => write!(f, "tried to call a function with return type {:?} \ passing return place of type {:?}", callee_ty, caller_ty), FunctionArgCountMismatch => write!(f, "tried to call a function with incorrect number of arguments"), BoundsCheck { ref len, ref index } => write!(f, "index out of bounds: the len is {:?} but the index is {:?}", len, index), ReallocatedWrongMemoryKind(ref old, ref new) => write!(f, "tried to reallocate memory from {} to {}", old, new), DeallocatedWrongMemoryKind(ref old, ref new) => write!(f, "tried to deallocate {} memory but gave {} as the kind", old, new), Intrinsic(ref err) => write!(f, "{}", err), InvalidChar(c) => write!(f, "tried to interpret an invalid 32-bit value as a char: {}", c), AlignmentCheckFailed { required, has } => write!(f, "tried to access memory with alignment {}, but alignment {} is required", has.bytes(), required.bytes()), TypeNotPrimitive(ty) => write!(f, "expected primitive type, got {}", ty), Layout(ref err) => write!(f, "rustc layout computation failed: {:?}", err), PathNotFound(ref path) => write!(f, "Cannot find path {:?}", path), MachineError(ref inner) => write!(f, "{}", inner), IncorrectAllocationInformation(size, size2, align, align2) => write!(f, "incorrect alloc info: expected size {} and align {}, \ got size {} and align {}", size.bytes(), align.bytes(), size2.bytes(), align2.bytes()), Panic { ref msg, line, col, ref file } => write!(f, "the evaluated program panicked at '{}', {}:{}:{}", msg, file, line, col), InvalidDiscriminant(val) => write!(f, "encountered invalid enum discriminant {}", val), _ => write!(f, "{}", self.description()), } } }
ReadBytesAsPointer => "a memory access tried to interpret some bytes as a pointer", ReadForeignStatic =>
random_line_split
CloudClusterPrinterStatus.py
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import List, Union, Dict, Optional, Any from cura.PrinterOutput.PrinterOutputController import PrinterOutputController from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel from .CloudClusterBuildPlate import CloudClusterBuildPlate from .CloudClusterPrintCoreConfiguration import CloudClusterPrintCoreConfiguration from .BaseCloudModel import BaseCloudModel ## Class representing a cluster printer # Spec: https://api-staging.ultimaker.com/connect/v1/spec class
(BaseCloudModel): ## Creates a new cluster printer status # \param enabled: A printer can be disabled if it should not receive new jobs. By default every printer is enabled. # \param firmware_version: Firmware version installed on the printer. Can differ for each printer in a cluster. # \param friendly_name: Human readable name of the printer. Can be used for identification purposes. # \param ip_address: The IP address of the printer in the local network. # \param machine_variant: The type of printer. Can be 'Ultimaker 3' or 'Ultimaker 3ext'. # \param status: The status of the printer. # \param unique_name: The unique name of the printer in the network. # \param uuid: The unique ID of the printer, also known as GUID. # \param configuration: The active print core configurations of this printer. # \param reserved_by: A printer can be claimed by a specific print job. # \param maintenance_required: Indicates if maintenance is necessary # \param firmware_update_status: Whether the printer's firmware is up-to-date, value is one of: "up_to_date", # "pending_update", "update_available", "update_in_progress", "update_failed", "update_impossible" # \param latest_available_firmware: The version of the latest firmware that is available # \param build_plate: The build plate that is on the printer def __init__(self, enabled: bool, firmware_version: str, friendly_name: str, ip_address: str, machine_variant: str, status: str, unique_name: str, uuid: str, configuration: List[Union[Dict[str, Any], CloudClusterPrintCoreConfiguration]], reserved_by: Optional[str] = None, maintenance_required: Optional[bool] = None, firmware_update_status: Optional[str] = None, latest_available_firmware: Optional[str] = None, build_plate: Union[Dict[str, Any], CloudClusterBuildPlate] = None, **kwargs) -> None: self.configuration = self.parseModels(CloudClusterPrintCoreConfiguration, configuration) self.enabled = enabled self.firmware_version = firmware_version self.friendly_name = friendly_name self.ip_address = ip_address self.machine_variant = machine_variant self.status = status self.unique_name = unique_name self.uuid = uuid self.reserved_by = reserved_by self.maintenance_required = maintenance_required self.firmware_update_status = firmware_update_status self.latest_available_firmware = latest_available_firmware self.build_plate = self.parseModel(CloudClusterBuildPlate, build_plate) if build_plate else None super().__init__(**kwargs) ## Creates a new output model. # \param controller - The controller of the model. def createOutputModel(self, controller: PrinterOutputController) -> PrinterOutputModel: model = PrinterOutputModel(controller, len(self.configuration), firmware_version = self.firmware_version) self.updateOutputModel(model) return model ## Updates the given output model. # \param model - The output model to update. def updateOutputModel(self, model: PrinterOutputModel) -> None: model.updateKey(self.uuid) model.updateName(self.friendly_name) model.updateType(self.machine_variant) model.updateState(self.status if self.enabled else "disabled") model.updateBuildplate(self.build_plate.type if self.build_plate else "glass") for configuration, extruder_output, extruder_config in \ zip(self.configuration, model.extruders, model.printerConfiguration.extruderConfigurations): configuration.updateOutputModel(extruder_output) configuration.updateConfigurationModel(extruder_config)
CloudClusterPrinterStatus
identifier_name
CloudClusterPrinterStatus.py
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import List, Union, Dict, Optional, Any from cura.PrinterOutput.PrinterOutputController import PrinterOutputController from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel from .CloudClusterBuildPlate import CloudClusterBuildPlate from .CloudClusterPrintCoreConfiguration import CloudClusterPrintCoreConfiguration from .BaseCloudModel import BaseCloudModel ## Class representing a cluster printer # Spec: https://api-staging.ultimaker.com/connect/v1/spec class CloudClusterPrinterStatus(BaseCloudModel): ## Creates a new cluster printer status # \param enabled: A printer can be disabled if it should not receive new jobs. By default every printer is enabled. # \param firmware_version: Firmware version installed on the printer. Can differ for each printer in a cluster. # \param friendly_name: Human readable name of the printer. Can be used for identification purposes. # \param ip_address: The IP address of the printer in the local network. # \param machine_variant: The type of printer. Can be 'Ultimaker 3' or 'Ultimaker 3ext'. # \param status: The status of the printer. # \param unique_name: The unique name of the printer in the network. # \param uuid: The unique ID of the printer, also known as GUID. # \param configuration: The active print core configurations of this printer. # \param reserved_by: A printer can be claimed by a specific print job. # \param maintenance_required: Indicates if maintenance is necessary # \param firmware_update_status: Whether the printer's firmware is up-to-date, value is one of: "up_to_date", # "pending_update", "update_available", "update_in_progress", "update_failed", "update_impossible" # \param latest_available_firmware: The version of the latest firmware that is available # \param build_plate: The build plate that is on the printer def __init__(self, enabled: bool, firmware_version: str, friendly_name: str, ip_address: str, machine_variant: str, status: str, unique_name: str, uuid: str, configuration: List[Union[Dict[str, Any], CloudClusterPrintCoreConfiguration]], reserved_by: Optional[str] = None, maintenance_required: Optional[bool] = None, firmware_update_status: Optional[str] = None, latest_available_firmware: Optional[str] = None, build_plate: Union[Dict[str, Any], CloudClusterBuildPlate] = None, **kwargs) -> None: self.configuration = self.parseModels(CloudClusterPrintCoreConfiguration, configuration) self.enabled = enabled self.firmware_version = firmware_version self.friendly_name = friendly_name self.ip_address = ip_address self.machine_variant = machine_variant self.status = status self.unique_name = unique_name self.uuid = uuid self.reserved_by = reserved_by self.maintenance_required = maintenance_required self.firmware_update_status = firmware_update_status self.latest_available_firmware = latest_available_firmware self.build_plate = self.parseModel(CloudClusterBuildPlate, build_plate) if build_plate else None super().__init__(**kwargs) ## Creates a new output model. # \param controller - The controller of the model. def createOutputModel(self, controller: PrinterOutputController) -> PrinterOutputModel:
## Updates the given output model. # \param model - The output model to update. def updateOutputModel(self, model: PrinterOutputModel) -> None: model.updateKey(self.uuid) model.updateName(self.friendly_name) model.updateType(self.machine_variant) model.updateState(self.status if self.enabled else "disabled") model.updateBuildplate(self.build_plate.type if self.build_plate else "glass") for configuration, extruder_output, extruder_config in \ zip(self.configuration, model.extruders, model.printerConfiguration.extruderConfigurations): configuration.updateOutputModel(extruder_output) configuration.updateConfigurationModel(extruder_config)
model = PrinterOutputModel(controller, len(self.configuration), firmware_version = self.firmware_version) self.updateOutputModel(model) return model
identifier_body
CloudClusterPrinterStatus.py
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import List, Union, Dict, Optional, Any from cura.PrinterOutput.PrinterOutputController import PrinterOutputController from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel from .CloudClusterBuildPlate import CloudClusterBuildPlate from .CloudClusterPrintCoreConfiguration import CloudClusterPrintCoreConfiguration from .BaseCloudModel import BaseCloudModel ## Class representing a cluster printer # Spec: https://api-staging.ultimaker.com/connect/v1/spec class CloudClusterPrinterStatus(BaseCloudModel): ## Creates a new cluster printer status # \param enabled: A printer can be disabled if it should not receive new jobs. By default every printer is enabled. # \param firmware_version: Firmware version installed on the printer. Can differ for each printer in a cluster. # \param friendly_name: Human readable name of the printer. Can be used for identification purposes. # \param ip_address: The IP address of the printer in the local network. # \param machine_variant: The type of printer. Can be 'Ultimaker 3' or 'Ultimaker 3ext'. # \param status: The status of the printer. # \param unique_name: The unique name of the printer in the network. # \param uuid: The unique ID of the printer, also known as GUID. # \param configuration: The active print core configurations of this printer. # \param reserved_by: A printer can be claimed by a specific print job. # \param maintenance_required: Indicates if maintenance is necessary # \param firmware_update_status: Whether the printer's firmware is up-to-date, value is one of: "up_to_date", # "pending_update", "update_available", "update_in_progress", "update_failed", "update_impossible" # \param latest_available_firmware: The version of the latest firmware that is available # \param build_plate: The build plate that is on the printer def __init__(self, enabled: bool, firmware_version: str, friendly_name: str, ip_address: str, machine_variant: str, status: str, unique_name: str, uuid: str, configuration: List[Union[Dict[str, Any], CloudClusterPrintCoreConfiguration]], reserved_by: Optional[str] = None, maintenance_required: Optional[bool] = None, firmware_update_status: Optional[str] = None, latest_available_firmware: Optional[str] = None, build_plate: Union[Dict[str, Any], CloudClusterBuildPlate] = None, **kwargs) -> None: self.configuration = self.parseModels(CloudClusterPrintCoreConfiguration, configuration) self.enabled = enabled self.firmware_version = firmware_version self.friendly_name = friendly_name self.ip_address = ip_address self.machine_variant = machine_variant self.status = status self.unique_name = unique_name self.uuid = uuid self.reserved_by = reserved_by self.maintenance_required = maintenance_required self.firmware_update_status = firmware_update_status self.latest_available_firmware = latest_available_firmware self.build_plate = self.parseModel(CloudClusterBuildPlate, build_plate) if build_plate else None super().__init__(**kwargs) ## Creates a new output model. # \param controller - The controller of the model. def createOutputModel(self, controller: PrinterOutputController) -> PrinterOutputModel: model = PrinterOutputModel(controller, len(self.configuration), firmware_version = self.firmware_version) self.updateOutputModel(model) return model ## Updates the given output model. # \param model - The output model to update. def updateOutputModel(self, model: PrinterOutputModel) -> None: model.updateKey(self.uuid) model.updateName(self.friendly_name) model.updateType(self.machine_variant) model.updateState(self.status if self.enabled else "disabled") model.updateBuildplate(self.build_plate.type if self.build_plate else "glass")
for configuration, extruder_output, extruder_config in \ zip(self.configuration, model.extruders, model.printerConfiguration.extruderConfigurations): configuration.updateOutputModel(extruder_output) configuration.updateConfigurationModel(extruder_config)
random_line_split
CloudClusterPrinterStatus.py
# Copyright (c) 2018 Ultimaker B.V. # Cura is released under the terms of the LGPLv3 or higher. from typing import List, Union, Dict, Optional, Any from cura.PrinterOutput.PrinterOutputController import PrinterOutputController from cura.PrinterOutput.Models.PrinterOutputModel import PrinterOutputModel from .CloudClusterBuildPlate import CloudClusterBuildPlate from .CloudClusterPrintCoreConfiguration import CloudClusterPrintCoreConfiguration from .BaseCloudModel import BaseCloudModel ## Class representing a cluster printer # Spec: https://api-staging.ultimaker.com/connect/v1/spec class CloudClusterPrinterStatus(BaseCloudModel): ## Creates a new cluster printer status # \param enabled: A printer can be disabled if it should not receive new jobs. By default every printer is enabled. # \param firmware_version: Firmware version installed on the printer. Can differ for each printer in a cluster. # \param friendly_name: Human readable name of the printer. Can be used for identification purposes. # \param ip_address: The IP address of the printer in the local network. # \param machine_variant: The type of printer. Can be 'Ultimaker 3' or 'Ultimaker 3ext'. # \param status: The status of the printer. # \param unique_name: The unique name of the printer in the network. # \param uuid: The unique ID of the printer, also known as GUID. # \param configuration: The active print core configurations of this printer. # \param reserved_by: A printer can be claimed by a specific print job. # \param maintenance_required: Indicates if maintenance is necessary # \param firmware_update_status: Whether the printer's firmware is up-to-date, value is one of: "up_to_date", # "pending_update", "update_available", "update_in_progress", "update_failed", "update_impossible" # \param latest_available_firmware: The version of the latest firmware that is available # \param build_plate: The build plate that is on the printer def __init__(self, enabled: bool, firmware_version: str, friendly_name: str, ip_address: str, machine_variant: str, status: str, unique_name: str, uuid: str, configuration: List[Union[Dict[str, Any], CloudClusterPrintCoreConfiguration]], reserved_by: Optional[str] = None, maintenance_required: Optional[bool] = None, firmware_update_status: Optional[str] = None, latest_available_firmware: Optional[str] = None, build_plate: Union[Dict[str, Any], CloudClusterBuildPlate] = None, **kwargs) -> None: self.configuration = self.parseModels(CloudClusterPrintCoreConfiguration, configuration) self.enabled = enabled self.firmware_version = firmware_version self.friendly_name = friendly_name self.ip_address = ip_address self.machine_variant = machine_variant self.status = status self.unique_name = unique_name self.uuid = uuid self.reserved_by = reserved_by self.maintenance_required = maintenance_required self.firmware_update_status = firmware_update_status self.latest_available_firmware = latest_available_firmware self.build_plate = self.parseModel(CloudClusterBuildPlate, build_plate) if build_plate else None super().__init__(**kwargs) ## Creates a new output model. # \param controller - The controller of the model. def createOutputModel(self, controller: PrinterOutputController) -> PrinterOutputModel: model = PrinterOutputModel(controller, len(self.configuration), firmware_version = self.firmware_version) self.updateOutputModel(model) return model ## Updates the given output model. # \param model - The output model to update. def updateOutputModel(self, model: PrinterOutputModel) -> None: model.updateKey(self.uuid) model.updateName(self.friendly_name) model.updateType(self.machine_variant) model.updateState(self.status if self.enabled else "disabled") model.updateBuildplate(self.build_plate.type if self.build_plate else "glass") for configuration, extruder_output, extruder_config in \ zip(self.configuration, model.extruders, model.printerConfiguration.extruderConfigurations):
configuration.updateOutputModel(extruder_output) configuration.updateConfigurationModel(extruder_config)
conditional_block
utils.py
""" CCX Enrollment operations for use by Coach APIs. Does not include any access control, be sure to check access before calling. """ import datetime import logging from contextlib import contextmanager from smtplib import SMTPException import pytz from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.core.validators import validate_email from django.utils.translation import ugettext as _ from courseware.courses import get_course_by_id from lms.djangoapps.ccx.custom_exception import CCXUserValidationException from lms.djangoapps.ccx.models import CustomCourseForEdX from lms.djangoapps.ccx.overrides import get_override_for_ccx from lms.djangoapps.instructor.access import allow_access, list_with_level, revoke_access from lms.djangoapps.instructor.enrollment import enroll_email, get_email_params, unenroll_email from lms.djangoapps.instructor.views.api import _split_input_list from lms.djangoapps.instructor.views.tools import get_student_from_identifier from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.content.course_structures.models import CourseStructure from student.models import CourseEnrollment, CourseEnrollmentException from student.roles import CourseCcxCoachRole, CourseInstructorRole, CourseStaffRole log = logging.getLogger("edx.ccx") def get_ccx_creation_dict(course): """ Return dict of rendering create ccx form. Arguments: course (CourseDescriptorWithMixins): An edx course Returns: dict: A attribute dict for view rendering """ context = { 'course': course, 'create_ccx_url': reverse('create_ccx', kwargs={'course_id': course.id}), 'has_ccx_connector': "true" if hasattr(course, 'ccx_connector') and course.ccx_connector else "false", 'use_ccx_con_error_message': _( "A CCX can only be created on this course through an external service." " Contact a course admin to give you access." ) } return context def get_ccx_from_ccx_locator(course_id): """ helper function to allow querying ccx fields from templates """ ccx_id = getattr(course_id, 'ccx', None) ccx = None if ccx_id: ccx = CustomCourseForEdX.objects.filter(id=ccx_id) if not ccx: log.warning( "CCX does not exist for course with id %s", course_id ) return None return ccx[0] def get_date(ccx, node, date_type=None, parent_node=None): """ This returns override or master date for section, subsection or a unit. :param ccx: ccx instance :param node: chapter, subsection or unit :param date_type: start or due :param parent_node: parent of node :return: start or due date """ date = get_override_for_ccx(ccx, node, date_type, None) if date_type == "start": master_date = node.start else: master_date = node.due if date is not None: # Setting override date [start or due] date = date.strftime('%Y-%m-%d %H:%M') elif not parent_node and master_date is not None: # Setting date from master course date = master_date.strftime('%Y-%m-%d %H:%M') elif parent_node is not None: # Set parent date (vertical has same dates as subsections) date = get_date(ccx, node=parent_node, date_type=date_type) return date def get_enrollment_action_and_identifiers(request): """ Extracts action type and student identifiers from the request on Enrollment tab of CCX Dashboard. """ action, identifiers = None, None student_action = request.POST.get('student-action', None) batch_action = request.POST.get('enrollment-button', None) if student_action: action = student_action student_id = request.POST.get('student-id', '') identifiers = [student_id] elif batch_action: action = batch_action identifiers_raw = request.POST.get('student-ids') identifiers = _split_input_list(identifiers_raw) return action, identifiers def validate_date(year, month, day, hour, minute): """ avoid corrupting db if bad dates come in """ valid = True if year < 0: valid = False if month < 1 or month > 12: valid = False if day < 1 or day > 31: valid = False if hour < 0 or hour > 23: valid = False if minute < 0 or minute > 59: valid = False return valid def parse_date(datestring): """ Generate a UTC datetime.datetime object from a string of the form 'YYYY-MM-DD HH:MM'. If string is empty or `None`, returns `None`. """ if datestring: date, time = datestring.split(' ') year, month, day = map(int, date.split('-')) hour, minute = map(int, time.split(':')) if validate_date(year, month, day, hour, minute): return datetime.datetime( year, month, day, hour, minute, tzinfo=pytz.UTC) return None def get_ccx_for_coach(course, coach): """ Looks to see if user is coach of a CCX for this course. Returns the CCX or None. """ ccxs = CustomCourseForEdX.objects.filter( course_id=course.id, coach=coach ) # XXX: In the future, it would be nice to support more than one ccx per # coach per course. This is a place where that might happen. if ccxs.exists(): return ccxs[0] return None def get_ccx_by_ccx_id(course, coach, ccx_id): """ Finds a CCX of given coach on given master course. Arguments: course (CourseDescriptor): Master course coach (User): Coach to ccx ccx_id (long): Id of ccx Returns: ccx (CustomCourseForEdX): Instance of CCX. """ try: ccx = CustomCourseForEdX.objects.get( id=ccx_id, course_id=course.id, coach=coach ) except CustomCourseForEdX.DoesNotExist: return None return ccx def get_valid_student_with_email(identifier): """ Helper function to get an user email from an identifier and validate it. In the UI a Coach can enroll users using both an email and an username. This function takes care of: - in case the identifier is an username, extracting the user object from the DB and then the associated email - validating the email Arguments: identifier (str): Username or email of the user to enroll Returns: (tuple): tuple containing: email (str): A validated email for the user to enroll. user (User): A valid User object or None. Raises: CCXUserValidationException: if the username is not found or the email is not valid. """ user = email = None try: user = get_student_from_identifier(identifier) except User.DoesNotExist: email = identifier else: email = user.email try: validate_email(email) except ValidationError: raise CCXUserValidationException('Could not find a user with name or email "{0}" '.format(identifier)) return email, user def ccx_students_enrolling_center(action, identifiers, email_students, course_key, email_params, coach): """ Function to enroll or unenroll/revoke students. Arguments: action (str): type of action to perform (Enroll, Unenroll/revoke) identifiers (list): list of students username/email email_students (bool): Flag to send an email to students course_key (CCXLocator): a CCX course key email_params (dict): dictionary of settings for the email to be sent coach (User): ccx coach Returns: list: list of error """ errors = [] if action == 'Enroll': ccx_course_overview = CourseOverview.get_from_id(course_key) course_locator = course_key.to_course_locator() staff = CourseStaffRole(course_locator).users_with_role() admins = CourseInstructorRole(course_locator).users_with_role() for identifier in identifiers: must_enroll = False try: email, student = get_valid_student_with_email(identifier) if student: must_enroll = student in staff or student in admins or student == coach except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue if CourseEnrollment.objects.is_course_full(ccx_course_overview) and not must_enroll: error = _('The course is full: the limit is {max_student_enrollments_allowed}').format( max_student_enrollments_allowed=ccx_course_overview.max_student_enrollments_allowed) log.info("%s", error) errors.append(error) break enroll_email(course_key, email, auto_enroll=True, email_students=email_students, email_params=email_params) elif action == 'Unenroll' or action == 'revoke': for identifier in identifiers: try: email, __ = get_valid_student_with_email(identifier) except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue unenroll_email(course_key, email, email_students=email_students, email_params=email_params) return errors @contextmanager def ccx_course(ccx_locator): """Create a context in which the course identified by course_locator exists """ course = get_course_by_id(ccx_locator) yield course def assign_staff_role_to_ccx(ccx_locator, user, master_course_id): """ Check if user has ccx_coach role on master course then assign him staff role on ccx only if role is not already assigned. Because of this coach can open dashboard from master course as well as ccx. :param ccx_locator: CCX key :param user: User to whom we want to assign role. :param master_course_id: Master course key """ coach_role_on_master_course = CourseCcxCoachRole(master_course_id) # check if user has coach role on master course if coach_role_on_master_course.has_user(user): # Check if user has staff role on ccx. role = CourseStaffRole(ccx_locator) if not role.has_user(user): # assign user the staff role on ccx with ccx_course(ccx_locator) as course: allow_access(course, user, "staff", send_email=False) def is_email(identifier): """ Checks if an `identifier` string is a valid email """ try: validate_email(identifier) except ValidationError: return False return True def get_course_chapters(course_key): """ Extracts the chapters from a course structure. If the course does not exist returns None. If the structure does not contain 1st level children, it returns an empty list. Args: course_key (CourseLocator): the course key Returns: list (string): a list of string representing the chapters modules of the course """ if course_key is None: return try: course_obj = CourseStructure.objects.get(course_id=course_key) except CourseStructure.DoesNotExist: return course_struct = course_obj.structure try: return course_struct['blocks'][course_struct['root']].get('children', []) except KeyError: return [] def
(master_course, ccx_key, display_name, send_email=True): """ Add staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on access grant. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') for staff in list_staff: # this call should be idempotent if staff not in list_staff_ccx: try: # Enroll the staff in the ccx enroll_email( course_id=ccx_key, student_email=staff.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'staff' access on ccx to staff of master course allow_access(course_ccx, staff, 'staff') except CourseEnrollmentException: log.warning( "Unable to enroll staff %s to course with id %s", staff.email, ccx_key ) continue except SMTPException: continue for instructor in list_instructor: # this call should be idempotent if instructor not in list_instructor_ccx: try: # Enroll the instructor in the ccx enroll_email( course_id=ccx_key, student_email=instructor.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'instructor' access on ccx to instructor of master course allow_access(course_ccx, instructor, 'instructor') except CourseEnrollmentException: log.warning( "Unable to enroll instructor %s to course with id %s", instructor.email, ccx_key ) continue except SMTPException: continue def remove_master_course_staff_from_ccx(master_course, ccx_key, display_name, send_email=True): """ Remove staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on revoke access. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) for staff in list_staff: if staff in list_staff_ccx: # revoke 'staff' access on ccx. revoke_access(course_ccx, staff, 'staff') # Unenroll the staff on ccx. unenroll_email( course_id=ccx_key, student_email=staff.email, email_students=send_email, email_params=email_params, ) for instructor in list_instructor: if instructor in list_instructor_ccx: # revoke 'instructor' access on ccx. revoke_access(course_ccx, instructor, 'instructor') # Unenroll the instructor on ccx. unenroll_email( course_id=ccx_key, student_email=instructor.email, email_students=send_email, email_params=email_params, )
add_master_course_staff_to_ccx
identifier_name
utils.py
""" CCX Enrollment operations for use by Coach APIs. Does not include any access control, be sure to check access before calling. """ import datetime import logging from contextlib import contextmanager from smtplib import SMTPException import pytz from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.core.validators import validate_email from django.utils.translation import ugettext as _ from courseware.courses import get_course_by_id from lms.djangoapps.ccx.custom_exception import CCXUserValidationException from lms.djangoapps.ccx.models import CustomCourseForEdX from lms.djangoapps.ccx.overrides import get_override_for_ccx from lms.djangoapps.instructor.access import allow_access, list_with_level, revoke_access from lms.djangoapps.instructor.enrollment import enroll_email, get_email_params, unenroll_email from lms.djangoapps.instructor.views.api import _split_input_list from lms.djangoapps.instructor.views.tools import get_student_from_identifier from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.content.course_structures.models import CourseStructure from student.models import CourseEnrollment, CourseEnrollmentException from student.roles import CourseCcxCoachRole, CourseInstructorRole, CourseStaffRole log = logging.getLogger("edx.ccx") def get_ccx_creation_dict(course): """ Return dict of rendering create ccx form. Arguments: course (CourseDescriptorWithMixins): An edx course Returns: dict: A attribute dict for view rendering """ context = { 'course': course, 'create_ccx_url': reverse('create_ccx', kwargs={'course_id': course.id}), 'has_ccx_connector': "true" if hasattr(course, 'ccx_connector') and course.ccx_connector else "false", 'use_ccx_con_error_message': _( "A CCX can only be created on this course through an external service." " Contact a course admin to give you access." ) } return context def get_ccx_from_ccx_locator(course_id): """ helper function to allow querying ccx fields from templates """ ccx_id = getattr(course_id, 'ccx', None) ccx = None if ccx_id: ccx = CustomCourseForEdX.objects.filter(id=ccx_id) if not ccx: log.warning( "CCX does not exist for course with id %s", course_id ) return None return ccx[0] def get_date(ccx, node, date_type=None, parent_node=None): """ This returns override or master date for section, subsection or a unit. :param ccx: ccx instance :param node: chapter, subsection or unit :param date_type: start or due :param parent_node: parent of node :return: start or due date """ date = get_override_for_ccx(ccx, node, date_type, None) if date_type == "start": master_date = node.start else: master_date = node.due if date is not None: # Setting override date [start or due] date = date.strftime('%Y-%m-%d %H:%M') elif not parent_node and master_date is not None: # Setting date from master course date = master_date.strftime('%Y-%m-%d %H:%M') elif parent_node is not None: # Set parent date (vertical has same dates as subsections) date = get_date(ccx, node=parent_node, date_type=date_type) return date def get_enrollment_action_and_identifiers(request): """ Extracts action type and student identifiers from the request on Enrollment tab of CCX Dashboard. """ action, identifiers = None, None student_action = request.POST.get('student-action', None) batch_action = request.POST.get('enrollment-button', None) if student_action: action = student_action student_id = request.POST.get('student-id', '') identifiers = [student_id] elif batch_action: action = batch_action identifiers_raw = request.POST.get('student-ids') identifiers = _split_input_list(identifiers_raw) return action, identifiers def validate_date(year, month, day, hour, minute): """ avoid corrupting db if bad dates come in """ valid = True if year < 0: valid = False if month < 1 or month > 12: valid = False if day < 1 or day > 31: valid = False if hour < 0 or hour > 23: valid = False if minute < 0 or minute > 59: valid = False return valid def parse_date(datestring): """ Generate a UTC datetime.datetime object from a string of the form 'YYYY-MM-DD HH:MM'. If string is empty or `None`, returns `None`. """ if datestring: date, time = datestring.split(' ') year, month, day = map(int, date.split('-')) hour, minute = map(int, time.split(':')) if validate_date(year, month, day, hour, minute): return datetime.datetime( year, month, day, hour, minute, tzinfo=pytz.UTC) return None def get_ccx_for_coach(course, coach): """ Looks to see if user is coach of a CCX for this course. Returns the CCX or None. """ ccxs = CustomCourseForEdX.objects.filter( course_id=course.id, coach=coach ) # XXX: In the future, it would be nice to support more than one ccx per # coach per course. This is a place where that might happen. if ccxs.exists(): return ccxs[0] return None def get_ccx_by_ccx_id(course, coach, ccx_id): """ Finds a CCX of given coach on given master course. Arguments: course (CourseDescriptor): Master course coach (User): Coach to ccx ccx_id (long): Id of ccx Returns: ccx (CustomCourseForEdX): Instance of CCX. """ try: ccx = CustomCourseForEdX.objects.get( id=ccx_id, course_id=course.id, coach=coach ) except CustomCourseForEdX.DoesNotExist: return None return ccx def get_valid_student_with_email(identifier): """ Helper function to get an user email from an identifier and validate it. In the UI a Coach can enroll users using both an email and an username. This function takes care of: - in case the identifier is an username, extracting the user object from the DB and then the associated email - validating the email Arguments: identifier (str): Username or email of the user to enroll Returns: (tuple): tuple containing: email (str): A validated email for the user to enroll. user (User): A valid User object or None. Raises: CCXUserValidationException: if the username is not found or the email is not valid. """ user = email = None try: user = get_student_from_identifier(identifier) except User.DoesNotExist: email = identifier else: email = user.email try: validate_email(email) except ValidationError: raise CCXUserValidationException('Could not find a user with name or email "{0}" '.format(identifier)) return email, user def ccx_students_enrolling_center(action, identifiers, email_students, course_key, email_params, coach): """ Function to enroll or unenroll/revoke students. Arguments: action (str): type of action to perform (Enroll, Unenroll/revoke) identifiers (list): list of students username/email email_students (bool): Flag to send an email to students course_key (CCXLocator): a CCX course key email_params (dict): dictionary of settings for the email to be sent coach (User): ccx coach Returns: list: list of error """ errors = [] if action == 'Enroll': ccx_course_overview = CourseOverview.get_from_id(course_key) course_locator = course_key.to_course_locator() staff = CourseStaffRole(course_locator).users_with_role() admins = CourseInstructorRole(course_locator).users_with_role() for identifier in identifiers: must_enroll = False try: email, student = get_valid_student_with_email(identifier) if student: must_enroll = student in staff or student in admins or student == coach except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue if CourseEnrollment.objects.is_course_full(ccx_course_overview) and not must_enroll: error = _('The course is full: the limit is {max_student_enrollments_allowed}').format( max_student_enrollments_allowed=ccx_course_overview.max_student_enrollments_allowed) log.info("%s", error) errors.append(error) break enroll_email(course_key, email, auto_enroll=True, email_students=email_students, email_params=email_params) elif action == 'Unenroll' or action == 'revoke': for identifier in identifiers: try: email, __ = get_valid_student_with_email(identifier) except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue unenroll_email(course_key, email, email_students=email_students, email_params=email_params) return errors @contextmanager def ccx_course(ccx_locator): """Create a context in which the course identified by course_locator exists """ course = get_course_by_id(ccx_locator) yield course def assign_staff_role_to_ccx(ccx_locator, user, master_course_id): """ Check if user has ccx_coach role on master course then assign him staff role on ccx only if role is not already assigned. Because of this coach can open dashboard from master course as well as ccx. :param ccx_locator: CCX key :param user: User to whom we want to assign role. :param master_course_id: Master course key """ coach_role_on_master_course = CourseCcxCoachRole(master_course_id) # check if user has coach role on master course if coach_role_on_master_course.has_user(user): # Check if user has staff role on ccx. role = CourseStaffRole(ccx_locator) if not role.has_user(user): # assign user the staff role on ccx with ccx_course(ccx_locator) as course: allow_access(course, user, "staff", send_email=False) def is_email(identifier): """ Checks if an `identifier` string is a valid email """ try: validate_email(identifier) except ValidationError: return False return True def get_course_chapters(course_key): """ Extracts the chapters from a course structure. If the course does not exist returns None. If the structure does not contain 1st level children, it returns an empty list. Args: course_key (CourseLocator): the course key Returns: list (string): a list of string representing the chapters modules of the course """ if course_key is None: return try: course_obj = CourseStructure.objects.get(course_id=course_key) except CourseStructure.DoesNotExist: return course_struct = course_obj.structure try: return course_struct['blocks'][course_struct['root']].get('children', []) except KeyError: return [] def add_master_course_staff_to_ccx(master_course, ccx_key, display_name, send_email=True): """ Add staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on access grant. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') for staff in list_staff: # this call should be idempotent if staff not in list_staff_ccx: try: # Enroll the staff in the ccx enroll_email( course_id=ccx_key, student_email=staff.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'staff' access on ccx to staff of master course allow_access(course_ccx, staff, 'staff') except CourseEnrollmentException: log.warning( "Unable to enroll staff %s to course with id %s", staff.email, ccx_key ) continue
continue for instructor in list_instructor: # this call should be idempotent if instructor not in list_instructor_ccx: try: # Enroll the instructor in the ccx enroll_email( course_id=ccx_key, student_email=instructor.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'instructor' access on ccx to instructor of master course allow_access(course_ccx, instructor, 'instructor') except CourseEnrollmentException: log.warning( "Unable to enroll instructor %s to course with id %s", instructor.email, ccx_key ) continue except SMTPException: continue def remove_master_course_staff_from_ccx(master_course, ccx_key, display_name, send_email=True): """ Remove staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on revoke access. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) for staff in list_staff: if staff in list_staff_ccx: # revoke 'staff' access on ccx. revoke_access(course_ccx, staff, 'staff') # Unenroll the staff on ccx. unenroll_email( course_id=ccx_key, student_email=staff.email, email_students=send_email, email_params=email_params, ) for instructor in list_instructor: if instructor in list_instructor_ccx: # revoke 'instructor' access on ccx. revoke_access(course_ccx, instructor, 'instructor') # Unenroll the instructor on ccx. unenroll_email( course_id=ccx_key, student_email=instructor.email, email_students=send_email, email_params=email_params, )
except SMTPException:
random_line_split
utils.py
""" CCX Enrollment operations for use by Coach APIs. Does not include any access control, be sure to check access before calling. """ import datetime import logging from contextlib import contextmanager from smtplib import SMTPException import pytz from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.core.validators import validate_email from django.utils.translation import ugettext as _ from courseware.courses import get_course_by_id from lms.djangoapps.ccx.custom_exception import CCXUserValidationException from lms.djangoapps.ccx.models import CustomCourseForEdX from lms.djangoapps.ccx.overrides import get_override_for_ccx from lms.djangoapps.instructor.access import allow_access, list_with_level, revoke_access from lms.djangoapps.instructor.enrollment import enroll_email, get_email_params, unenroll_email from lms.djangoapps.instructor.views.api import _split_input_list from lms.djangoapps.instructor.views.tools import get_student_from_identifier from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.content.course_structures.models import CourseStructure from student.models import CourseEnrollment, CourseEnrollmentException from student.roles import CourseCcxCoachRole, CourseInstructorRole, CourseStaffRole log = logging.getLogger("edx.ccx") def get_ccx_creation_dict(course): """ Return dict of rendering create ccx form. Arguments: course (CourseDescriptorWithMixins): An edx course Returns: dict: A attribute dict for view rendering """ context = { 'course': course, 'create_ccx_url': reverse('create_ccx', kwargs={'course_id': course.id}), 'has_ccx_connector': "true" if hasattr(course, 'ccx_connector') and course.ccx_connector else "false", 'use_ccx_con_error_message': _( "A CCX can only be created on this course through an external service." " Contact a course admin to give you access." ) } return context def get_ccx_from_ccx_locator(course_id): """ helper function to allow querying ccx fields from templates """ ccx_id = getattr(course_id, 'ccx', None) ccx = None if ccx_id: ccx = CustomCourseForEdX.objects.filter(id=ccx_id) if not ccx:
return ccx[0] def get_date(ccx, node, date_type=None, parent_node=None): """ This returns override or master date for section, subsection or a unit. :param ccx: ccx instance :param node: chapter, subsection or unit :param date_type: start or due :param parent_node: parent of node :return: start or due date """ date = get_override_for_ccx(ccx, node, date_type, None) if date_type == "start": master_date = node.start else: master_date = node.due if date is not None: # Setting override date [start or due] date = date.strftime('%Y-%m-%d %H:%M') elif not parent_node and master_date is not None: # Setting date from master course date = master_date.strftime('%Y-%m-%d %H:%M') elif parent_node is not None: # Set parent date (vertical has same dates as subsections) date = get_date(ccx, node=parent_node, date_type=date_type) return date def get_enrollment_action_and_identifiers(request): """ Extracts action type and student identifiers from the request on Enrollment tab of CCX Dashboard. """ action, identifiers = None, None student_action = request.POST.get('student-action', None) batch_action = request.POST.get('enrollment-button', None) if student_action: action = student_action student_id = request.POST.get('student-id', '') identifiers = [student_id] elif batch_action: action = batch_action identifiers_raw = request.POST.get('student-ids') identifiers = _split_input_list(identifiers_raw) return action, identifiers def validate_date(year, month, day, hour, minute): """ avoid corrupting db if bad dates come in """ valid = True if year < 0: valid = False if month < 1 or month > 12: valid = False if day < 1 or day > 31: valid = False if hour < 0 or hour > 23: valid = False if minute < 0 or minute > 59: valid = False return valid def parse_date(datestring): """ Generate a UTC datetime.datetime object from a string of the form 'YYYY-MM-DD HH:MM'. If string is empty or `None`, returns `None`. """ if datestring: date, time = datestring.split(' ') year, month, day = map(int, date.split('-')) hour, minute = map(int, time.split(':')) if validate_date(year, month, day, hour, minute): return datetime.datetime( year, month, day, hour, minute, tzinfo=pytz.UTC) return None def get_ccx_for_coach(course, coach): """ Looks to see if user is coach of a CCX for this course. Returns the CCX or None. """ ccxs = CustomCourseForEdX.objects.filter( course_id=course.id, coach=coach ) # XXX: In the future, it would be nice to support more than one ccx per # coach per course. This is a place where that might happen. if ccxs.exists(): return ccxs[0] return None def get_ccx_by_ccx_id(course, coach, ccx_id): """ Finds a CCX of given coach on given master course. Arguments: course (CourseDescriptor): Master course coach (User): Coach to ccx ccx_id (long): Id of ccx Returns: ccx (CustomCourseForEdX): Instance of CCX. """ try: ccx = CustomCourseForEdX.objects.get( id=ccx_id, course_id=course.id, coach=coach ) except CustomCourseForEdX.DoesNotExist: return None return ccx def get_valid_student_with_email(identifier): """ Helper function to get an user email from an identifier and validate it. In the UI a Coach can enroll users using both an email and an username. This function takes care of: - in case the identifier is an username, extracting the user object from the DB and then the associated email - validating the email Arguments: identifier (str): Username or email of the user to enroll Returns: (tuple): tuple containing: email (str): A validated email for the user to enroll. user (User): A valid User object or None. Raises: CCXUserValidationException: if the username is not found or the email is not valid. """ user = email = None try: user = get_student_from_identifier(identifier) except User.DoesNotExist: email = identifier else: email = user.email try: validate_email(email) except ValidationError: raise CCXUserValidationException('Could not find a user with name or email "{0}" '.format(identifier)) return email, user def ccx_students_enrolling_center(action, identifiers, email_students, course_key, email_params, coach): """ Function to enroll or unenroll/revoke students. Arguments: action (str): type of action to perform (Enroll, Unenroll/revoke) identifiers (list): list of students username/email email_students (bool): Flag to send an email to students course_key (CCXLocator): a CCX course key email_params (dict): dictionary of settings for the email to be sent coach (User): ccx coach Returns: list: list of error """ errors = [] if action == 'Enroll': ccx_course_overview = CourseOverview.get_from_id(course_key) course_locator = course_key.to_course_locator() staff = CourseStaffRole(course_locator).users_with_role() admins = CourseInstructorRole(course_locator).users_with_role() for identifier in identifiers: must_enroll = False try: email, student = get_valid_student_with_email(identifier) if student: must_enroll = student in staff or student in admins or student == coach except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue if CourseEnrollment.objects.is_course_full(ccx_course_overview) and not must_enroll: error = _('The course is full: the limit is {max_student_enrollments_allowed}').format( max_student_enrollments_allowed=ccx_course_overview.max_student_enrollments_allowed) log.info("%s", error) errors.append(error) break enroll_email(course_key, email, auto_enroll=True, email_students=email_students, email_params=email_params) elif action == 'Unenroll' or action == 'revoke': for identifier in identifiers: try: email, __ = get_valid_student_with_email(identifier) except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue unenroll_email(course_key, email, email_students=email_students, email_params=email_params) return errors @contextmanager def ccx_course(ccx_locator): """Create a context in which the course identified by course_locator exists """ course = get_course_by_id(ccx_locator) yield course def assign_staff_role_to_ccx(ccx_locator, user, master_course_id): """ Check if user has ccx_coach role on master course then assign him staff role on ccx only if role is not already assigned. Because of this coach can open dashboard from master course as well as ccx. :param ccx_locator: CCX key :param user: User to whom we want to assign role. :param master_course_id: Master course key """ coach_role_on_master_course = CourseCcxCoachRole(master_course_id) # check if user has coach role on master course if coach_role_on_master_course.has_user(user): # Check if user has staff role on ccx. role = CourseStaffRole(ccx_locator) if not role.has_user(user): # assign user the staff role on ccx with ccx_course(ccx_locator) as course: allow_access(course, user, "staff", send_email=False) def is_email(identifier): """ Checks if an `identifier` string is a valid email """ try: validate_email(identifier) except ValidationError: return False return True def get_course_chapters(course_key): """ Extracts the chapters from a course structure. If the course does not exist returns None. If the structure does not contain 1st level children, it returns an empty list. Args: course_key (CourseLocator): the course key Returns: list (string): a list of string representing the chapters modules of the course """ if course_key is None: return try: course_obj = CourseStructure.objects.get(course_id=course_key) except CourseStructure.DoesNotExist: return course_struct = course_obj.structure try: return course_struct['blocks'][course_struct['root']].get('children', []) except KeyError: return [] def add_master_course_staff_to_ccx(master_course, ccx_key, display_name, send_email=True): """ Add staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on access grant. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') for staff in list_staff: # this call should be idempotent if staff not in list_staff_ccx: try: # Enroll the staff in the ccx enroll_email( course_id=ccx_key, student_email=staff.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'staff' access on ccx to staff of master course allow_access(course_ccx, staff, 'staff') except CourseEnrollmentException: log.warning( "Unable to enroll staff %s to course with id %s", staff.email, ccx_key ) continue except SMTPException: continue for instructor in list_instructor: # this call should be idempotent if instructor not in list_instructor_ccx: try: # Enroll the instructor in the ccx enroll_email( course_id=ccx_key, student_email=instructor.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'instructor' access on ccx to instructor of master course allow_access(course_ccx, instructor, 'instructor') except CourseEnrollmentException: log.warning( "Unable to enroll instructor %s to course with id %s", instructor.email, ccx_key ) continue except SMTPException: continue def remove_master_course_staff_from_ccx(master_course, ccx_key, display_name, send_email=True): """ Remove staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on revoke access. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) for staff in list_staff: if staff in list_staff_ccx: # revoke 'staff' access on ccx. revoke_access(course_ccx, staff, 'staff') # Unenroll the staff on ccx. unenroll_email( course_id=ccx_key, student_email=staff.email, email_students=send_email, email_params=email_params, ) for instructor in list_instructor: if instructor in list_instructor_ccx: # revoke 'instructor' access on ccx. revoke_access(course_ccx, instructor, 'instructor') # Unenroll the instructor on ccx. unenroll_email( course_id=ccx_key, student_email=instructor.email, email_students=send_email, email_params=email_params, )
log.warning( "CCX does not exist for course with id %s", course_id ) return None
conditional_block
utils.py
""" CCX Enrollment operations for use by Coach APIs. Does not include any access control, be sure to check access before calling. """ import datetime import logging from contextlib import contextmanager from smtplib import SMTPException import pytz from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.core.urlresolvers import reverse from django.core.validators import validate_email from django.utils.translation import ugettext as _ from courseware.courses import get_course_by_id from lms.djangoapps.ccx.custom_exception import CCXUserValidationException from lms.djangoapps.ccx.models import CustomCourseForEdX from lms.djangoapps.ccx.overrides import get_override_for_ccx from lms.djangoapps.instructor.access import allow_access, list_with_level, revoke_access from lms.djangoapps.instructor.enrollment import enroll_email, get_email_params, unenroll_email from lms.djangoapps.instructor.views.api import _split_input_list from lms.djangoapps.instructor.views.tools import get_student_from_identifier from openedx.core.djangoapps.content.course_overviews.models import CourseOverview from openedx.core.djangoapps.content.course_structures.models import CourseStructure from student.models import CourseEnrollment, CourseEnrollmentException from student.roles import CourseCcxCoachRole, CourseInstructorRole, CourseStaffRole log = logging.getLogger("edx.ccx") def get_ccx_creation_dict(course): """ Return dict of rendering create ccx form. Arguments: course (CourseDescriptorWithMixins): An edx course Returns: dict: A attribute dict for view rendering """ context = { 'course': course, 'create_ccx_url': reverse('create_ccx', kwargs={'course_id': course.id}), 'has_ccx_connector': "true" if hasattr(course, 'ccx_connector') and course.ccx_connector else "false", 'use_ccx_con_error_message': _( "A CCX can only be created on this course through an external service." " Contact a course admin to give you access." ) } return context def get_ccx_from_ccx_locator(course_id): """ helper function to allow querying ccx fields from templates """ ccx_id = getattr(course_id, 'ccx', None) ccx = None if ccx_id: ccx = CustomCourseForEdX.objects.filter(id=ccx_id) if not ccx: log.warning( "CCX does not exist for course with id %s", course_id ) return None return ccx[0] def get_date(ccx, node, date_type=None, parent_node=None): """ This returns override or master date for section, subsection or a unit. :param ccx: ccx instance :param node: chapter, subsection or unit :param date_type: start or due :param parent_node: parent of node :return: start or due date """ date = get_override_for_ccx(ccx, node, date_type, None) if date_type == "start": master_date = node.start else: master_date = node.due if date is not None: # Setting override date [start or due] date = date.strftime('%Y-%m-%d %H:%M') elif not parent_node and master_date is not None: # Setting date from master course date = master_date.strftime('%Y-%m-%d %H:%M') elif parent_node is not None: # Set parent date (vertical has same dates as subsections) date = get_date(ccx, node=parent_node, date_type=date_type) return date def get_enrollment_action_and_identifiers(request): """ Extracts action type and student identifiers from the request on Enrollment tab of CCX Dashboard. """ action, identifiers = None, None student_action = request.POST.get('student-action', None) batch_action = request.POST.get('enrollment-button', None) if student_action: action = student_action student_id = request.POST.get('student-id', '') identifiers = [student_id] elif batch_action: action = batch_action identifiers_raw = request.POST.get('student-ids') identifiers = _split_input_list(identifiers_raw) return action, identifiers def validate_date(year, month, day, hour, minute): """ avoid corrupting db if bad dates come in """ valid = True if year < 0: valid = False if month < 1 or month > 12: valid = False if day < 1 or day > 31: valid = False if hour < 0 or hour > 23: valid = False if minute < 0 or minute > 59: valid = False return valid def parse_date(datestring): """ Generate a UTC datetime.datetime object from a string of the form 'YYYY-MM-DD HH:MM'. If string is empty or `None`, returns `None`. """ if datestring: date, time = datestring.split(' ') year, month, day = map(int, date.split('-')) hour, minute = map(int, time.split(':')) if validate_date(year, month, day, hour, minute): return datetime.datetime( year, month, day, hour, minute, tzinfo=pytz.UTC) return None def get_ccx_for_coach(course, coach): """ Looks to see if user is coach of a CCX for this course. Returns the CCX or None. """ ccxs = CustomCourseForEdX.objects.filter( course_id=course.id, coach=coach ) # XXX: In the future, it would be nice to support more than one ccx per # coach per course. This is a place where that might happen. if ccxs.exists(): return ccxs[0] return None def get_ccx_by_ccx_id(course, coach, ccx_id): """ Finds a CCX of given coach on given master course. Arguments: course (CourseDescriptor): Master course coach (User): Coach to ccx ccx_id (long): Id of ccx Returns: ccx (CustomCourseForEdX): Instance of CCX. """ try: ccx = CustomCourseForEdX.objects.get( id=ccx_id, course_id=course.id, coach=coach ) except CustomCourseForEdX.DoesNotExist: return None return ccx def get_valid_student_with_email(identifier): """ Helper function to get an user email from an identifier and validate it. In the UI a Coach can enroll users using both an email and an username. This function takes care of: - in case the identifier is an username, extracting the user object from the DB and then the associated email - validating the email Arguments: identifier (str): Username or email of the user to enroll Returns: (tuple): tuple containing: email (str): A validated email for the user to enroll. user (User): A valid User object or None. Raises: CCXUserValidationException: if the username is not found or the email is not valid. """ user = email = None try: user = get_student_from_identifier(identifier) except User.DoesNotExist: email = identifier else: email = user.email try: validate_email(email) except ValidationError: raise CCXUserValidationException('Could not find a user with name or email "{0}" '.format(identifier)) return email, user def ccx_students_enrolling_center(action, identifiers, email_students, course_key, email_params, coach):
@contextmanager def ccx_course(ccx_locator): """Create a context in which the course identified by course_locator exists """ course = get_course_by_id(ccx_locator) yield course def assign_staff_role_to_ccx(ccx_locator, user, master_course_id): """ Check if user has ccx_coach role on master course then assign him staff role on ccx only if role is not already assigned. Because of this coach can open dashboard from master course as well as ccx. :param ccx_locator: CCX key :param user: User to whom we want to assign role. :param master_course_id: Master course key """ coach_role_on_master_course = CourseCcxCoachRole(master_course_id) # check if user has coach role on master course if coach_role_on_master_course.has_user(user): # Check if user has staff role on ccx. role = CourseStaffRole(ccx_locator) if not role.has_user(user): # assign user the staff role on ccx with ccx_course(ccx_locator) as course: allow_access(course, user, "staff", send_email=False) def is_email(identifier): """ Checks if an `identifier` string is a valid email """ try: validate_email(identifier) except ValidationError: return False return True def get_course_chapters(course_key): """ Extracts the chapters from a course structure. If the course does not exist returns None. If the structure does not contain 1st level children, it returns an empty list. Args: course_key (CourseLocator): the course key Returns: list (string): a list of string representing the chapters modules of the course """ if course_key is None: return try: course_obj = CourseStructure.objects.get(course_id=course_key) except CourseStructure.DoesNotExist: return course_struct = course_obj.structure try: return course_struct['blocks'][course_struct['root']].get('children', []) except KeyError: return [] def add_master_course_staff_to_ccx(master_course, ccx_key, display_name, send_email=True): """ Add staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on access grant. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') for staff in list_staff: # this call should be idempotent if staff not in list_staff_ccx: try: # Enroll the staff in the ccx enroll_email( course_id=ccx_key, student_email=staff.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'staff' access on ccx to staff of master course allow_access(course_ccx, staff, 'staff') except CourseEnrollmentException: log.warning( "Unable to enroll staff %s to course with id %s", staff.email, ccx_key ) continue except SMTPException: continue for instructor in list_instructor: # this call should be idempotent if instructor not in list_instructor_ccx: try: # Enroll the instructor in the ccx enroll_email( course_id=ccx_key, student_email=instructor.email, auto_enroll=True, email_students=send_email, email_params=email_params, ) # allow 'instructor' access on ccx to instructor of master course allow_access(course_ccx, instructor, 'instructor') except CourseEnrollmentException: log.warning( "Unable to enroll instructor %s to course with id %s", instructor.email, ccx_key ) continue except SMTPException: continue def remove_master_course_staff_from_ccx(master_course, ccx_key, display_name, send_email=True): """ Remove staff and instructor roles on ccx to all the staff and instructors members of master course. Arguments: master_course (CourseDescriptorWithMixins): Master course instance. ccx_key (CCXLocator): CCX course key. display_name (str): ccx display name for email. send_email (bool): flag to switch on or off email to the users on revoke access. """ list_staff = list_with_level(master_course, 'staff') list_instructor = list_with_level(master_course, 'instructor') with ccx_course(ccx_key) as course_ccx: list_staff_ccx = list_with_level(course_ccx, 'staff') list_instructor_ccx = list_with_level(course_ccx, 'instructor') email_params = get_email_params(course_ccx, auto_enroll=True, course_key=ccx_key, display_name=display_name) for staff in list_staff: if staff in list_staff_ccx: # revoke 'staff' access on ccx. revoke_access(course_ccx, staff, 'staff') # Unenroll the staff on ccx. unenroll_email( course_id=ccx_key, student_email=staff.email, email_students=send_email, email_params=email_params, ) for instructor in list_instructor: if instructor in list_instructor_ccx: # revoke 'instructor' access on ccx. revoke_access(course_ccx, instructor, 'instructor') # Unenroll the instructor on ccx. unenroll_email( course_id=ccx_key, student_email=instructor.email, email_students=send_email, email_params=email_params, )
""" Function to enroll or unenroll/revoke students. Arguments: action (str): type of action to perform (Enroll, Unenroll/revoke) identifiers (list): list of students username/email email_students (bool): Flag to send an email to students course_key (CCXLocator): a CCX course key email_params (dict): dictionary of settings for the email to be sent coach (User): ccx coach Returns: list: list of error """ errors = [] if action == 'Enroll': ccx_course_overview = CourseOverview.get_from_id(course_key) course_locator = course_key.to_course_locator() staff = CourseStaffRole(course_locator).users_with_role() admins = CourseInstructorRole(course_locator).users_with_role() for identifier in identifiers: must_enroll = False try: email, student = get_valid_student_with_email(identifier) if student: must_enroll = student in staff or student in admins or student == coach except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue if CourseEnrollment.objects.is_course_full(ccx_course_overview) and not must_enroll: error = _('The course is full: the limit is {max_student_enrollments_allowed}').format( max_student_enrollments_allowed=ccx_course_overview.max_student_enrollments_allowed) log.info("%s", error) errors.append(error) break enroll_email(course_key, email, auto_enroll=True, email_students=email_students, email_params=email_params) elif action == 'Unenroll' or action == 'revoke': for identifier in identifiers: try: email, __ = get_valid_student_with_email(identifier) except CCXUserValidationException as exp: log.info("%s", exp) errors.append("{0}".format(exp)) continue unenroll_email(course_key, email, email_students=email_students, email_params=email_params) return errors
identifier_body
item-attributes.rs
// Copyright 2012 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. // These are attributes of the implicit crate. Really this just needs to parse // for completeness since .rs files linked from .rc files support this // notation to specify their module's attributes #[attr1 = "val"]; #[attr2 = "val"]; #[attr3]; #[attr4(attr5)]; // Special linkage attributes for the crate #[link(name = "extra", vers = "0.1", uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297", url = "http://rust-lang.org/src/extra")]; // These are attributes of the following mod #[attr1 = "val"] #[attr2 = "val"] mod test_first_item_in_file_mod {} mod test_single_attr_outer { #[attr = "val"] pub static x: int = 10; #[attr = "val"] pub fn f() { } #[attr = "val"] pub mod mod1 {} pub mod rustrt { #[attr = "val"] extern {} } } mod test_multi_attr_outer { #[attr1 = "val"] #[attr2 = "val"] pub static x: int = 10; #[attr1 = "val"] #[attr2 = "val"] pub fn f()
#[attr1 = "val"] #[attr2 = "val"] pub mod mod1 {} pub mod rustrt { #[attr1 = "val"] #[attr2 = "val"] extern {} } #[attr1 = "val"] #[attr2 = "val"] struct t {x: int} } mod test_stmt_single_attr_outer { pub fn f() { #[attr = "val"] static x: int = 10; #[attr = "val"] fn f() { } #[attr = "val"] mod mod1 { } mod rustrt { #[attr = "val"] extern { } } } } mod test_stmt_multi_attr_outer { pub fn f() { #[attr1 = "val"] #[attr2 = "val"] static x: int = 10; #[attr1 = "val"] #[attr2 = "val"] fn f() { } /* FIXME: Issue #493 #[attr1 = "val"] #[attr2 = "val"] mod mod1 { } pub mod rustrt { #[attr1 = "val"] #[attr2 = "val"] extern { } } */ } } mod test_attr_inner { pub mod m { // This is an attribute of mod m #[attr = "val"]; } } mod test_attr_inner_then_outer { pub mod m { // This is an attribute of mod m #[attr = "val"]; // This is an attribute of fn f #[attr = "val"] fn f() { } } } mod test_attr_inner_then_outer_multi { pub mod m { // This is an attribute of mod m #[attr1 = "val"]; #[attr2 = "val"]; // This is an attribute of fn f #[attr1 = "val"] #[attr2 = "val"] fn f() { } } } mod test_distinguish_syntax_ext { extern mod extra; pub fn f() { format!("test{}", "s"); #[attr = "val"] fn g() { } } } mod test_other_forms { #[attr] #[attr(word)] #[attr(attr(word))] #[attr(key1 = "val", key2 = "val", attr)] pub fn f() { } } mod test_foreign_items { pub mod rustrt { use std::libc; extern { #[attr]; #[attr] fn rust_get_test_int() -> libc::intptr_t; } } } mod test_literals { #[str = "s"]; #[char = 'c']; #[int = 100]; #[uint = 100u]; #[mach_int = 100u32]; #[float = 1.0]; #[mach_float = 1.0f32]; #[nil = ()]; #[bool = true]; mod m {} } fn test_fn_inner() { #[inner_fn_attr]; } pub fn main() { }
{ }
identifier_body
item-attributes.rs
// Copyright 2012 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. // These are attributes of the implicit crate. Really this just needs to parse // for completeness since .rs files linked from .rc files support this // notation to specify their module's attributes #[attr1 = "val"]; #[attr2 = "val"]; #[attr3]; #[attr4(attr5)]; // Special linkage attributes for the crate #[link(name = "extra", vers = "0.1", uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297", url = "http://rust-lang.org/src/extra")]; // These are attributes of the following mod #[attr1 = "val"] #[attr2 = "val"] mod test_first_item_in_file_mod {} mod test_single_attr_outer { #[attr = "val"] pub static x: int = 10; #[attr = "val"] pub fn f() { } #[attr = "val"] pub mod mod1 {} pub mod rustrt { #[attr = "val"] extern {} } } mod test_multi_attr_outer { #[attr1 = "val"] #[attr2 = "val"] pub static x: int = 10; #[attr1 = "val"] #[attr2 = "val"] pub fn f() { } #[attr1 = "val"] #[attr2 = "val"] pub mod mod1 {} pub mod rustrt { #[attr1 = "val"] #[attr2 = "val"] extern {} } #[attr1 = "val"] #[attr2 = "val"] struct t {x: int} } mod test_stmt_single_attr_outer { pub fn f() { #[attr = "val"] static x: int = 10; #[attr = "val"] fn f() { } #[attr = "val"] mod mod1 { } mod rustrt { #[attr = "val"] extern { } } } } mod test_stmt_multi_attr_outer { pub fn f() { #[attr1 = "val"] #[attr2 = "val"] static x: int = 10; #[attr1 = "val"] #[attr2 = "val"] fn f() { } /* FIXME: Issue #493 #[attr1 = "val"] #[attr2 = "val"] mod mod1 { } pub mod rustrt { #[attr1 = "val"] #[attr2 = "val"] extern { } } */ } } mod test_attr_inner { pub mod m { // This is an attribute of mod m #[attr = "val"]; } } mod test_attr_inner_then_outer { pub mod m { // This is an attribute of mod m #[attr = "val"]; // This is an attribute of fn f #[attr = "val"] fn f() { } } } mod test_attr_inner_then_outer_multi { pub mod m { // This is an attribute of mod m #[attr1 = "val"]; #[attr2 = "val"]; // This is an attribute of fn f #[attr1 = "val"] #[attr2 = "val"] fn f() { } } } mod test_distinguish_syntax_ext { extern mod extra; pub fn f() { format!("test{}", "s"); #[attr = "val"] fn g() { } } } mod test_other_forms { #[attr] #[attr(word)] #[attr(attr(word))] #[attr(key1 = "val", key2 = "val", attr)] pub fn f() { } } mod test_foreign_items { pub mod rustrt { use std::libc;
extern { #[attr]; #[attr] fn rust_get_test_int() -> libc::intptr_t; } } } mod test_literals { #[str = "s"]; #[char = 'c']; #[int = 100]; #[uint = 100u]; #[mach_int = 100u32]; #[float = 1.0]; #[mach_float = 1.0f32]; #[nil = ()]; #[bool = true]; mod m {} } fn test_fn_inner() { #[inner_fn_attr]; } pub fn main() { }
random_line_split
item-attributes.rs
// Copyright 2012 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. // These are attributes of the implicit crate. Really this just needs to parse // for completeness since .rs files linked from .rc files support this // notation to specify their module's attributes #[attr1 = "val"]; #[attr2 = "val"]; #[attr3]; #[attr4(attr5)]; // Special linkage attributes for the crate #[link(name = "extra", vers = "0.1", uuid = "122bed0b-c19b-4b82-b0b7-7ae8aead7297", url = "http://rust-lang.org/src/extra")]; // These are attributes of the following mod #[attr1 = "val"] #[attr2 = "val"] mod test_first_item_in_file_mod {} mod test_single_attr_outer { #[attr = "val"] pub static x: int = 10; #[attr = "val"] pub fn f() { } #[attr = "val"] pub mod mod1 {} pub mod rustrt { #[attr = "val"] extern {} } } mod test_multi_attr_outer { #[attr1 = "val"] #[attr2 = "val"] pub static x: int = 10; #[attr1 = "val"] #[attr2 = "val"] pub fn f() { } #[attr1 = "val"] #[attr2 = "val"] pub mod mod1 {} pub mod rustrt { #[attr1 = "val"] #[attr2 = "val"] extern {} } #[attr1 = "val"] #[attr2 = "val"] struct t {x: int} } mod test_stmt_single_attr_outer { pub fn f() { #[attr = "val"] static x: int = 10; #[attr = "val"] fn f() { } #[attr = "val"] mod mod1 { } mod rustrt { #[attr = "val"] extern { } } } } mod test_stmt_multi_attr_outer { pub fn f() { #[attr1 = "val"] #[attr2 = "val"] static x: int = 10; #[attr1 = "val"] #[attr2 = "val"] fn f() { } /* FIXME: Issue #493 #[attr1 = "val"] #[attr2 = "val"] mod mod1 { } pub mod rustrt { #[attr1 = "val"] #[attr2 = "val"] extern { } } */ } } mod test_attr_inner { pub mod m { // This is an attribute of mod m #[attr = "val"]; } } mod test_attr_inner_then_outer { pub mod m { // This is an attribute of mod m #[attr = "val"]; // This is an attribute of fn f #[attr = "val"] fn f() { } } } mod test_attr_inner_then_outer_multi { pub mod m { // This is an attribute of mod m #[attr1 = "val"]; #[attr2 = "val"]; // This is an attribute of fn f #[attr1 = "val"] #[attr2 = "val"] fn f() { } } } mod test_distinguish_syntax_ext { extern mod extra; pub fn f() { format!("test{}", "s"); #[attr = "val"] fn g() { } } } mod test_other_forms { #[attr] #[attr(word)] #[attr(attr(word))] #[attr(key1 = "val", key2 = "val", attr)] pub fn
() { } } mod test_foreign_items { pub mod rustrt { use std::libc; extern { #[attr]; #[attr] fn rust_get_test_int() -> libc::intptr_t; } } } mod test_literals { #[str = "s"]; #[char = 'c']; #[int = 100]; #[uint = 100u]; #[mach_int = 100u32]; #[float = 1.0]; #[mach_float = 1.0f32]; #[nil = ()]; #[bool = true]; mod m {} } fn test_fn_inner() { #[inner_fn_attr]; } pub fn main() { }
f
identifier_name
lib.rs
// Copyright 2012-2014 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. //! Support code for encoding and decoding types. //! //! # Usage //! //! This crate is [on crates.io](https://crates.io/crates/rustc-serialize) and //! can be used by adding `rustc-serialize` to the dependencies in your //! project's `Cargo.toml`. //! //! ```toml //! [dependencies] //! rustc-serialize = "0.3" //! ``` //! //! and this to your crate root: //! //! ```rust //! extern crate rustc_serialize; //! ``` #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "https://www.rust-lang.org/favicon.ico", html_root_url = "https://doc.rust-lang.org/rustc-serialize/")] #![cfg_attr(test, deny(warnings))] #![allow(trivial_numeric_casts)] #![cfg_attr(rust_build, feature(staged_api))]
#![cfg_attr(rust_build, unstable(feature = "rustc_private", reason = "use the crates.io `rustc-serialize` library instead"))] #[cfg(test)] extern crate rand; pub use self::serialize::{Decoder, Encoder, Decodable, Encodable, DecoderHelpers, EncoderHelpers}; mod serialize; mod collection_impls; pub mod base64; pub mod hex; pub mod json; mod rustc_serialize { pub use serialize::*; }
#![cfg_attr(rust_build, staged_api)]
random_line_split
db.ts
/// Module for interacting with the mongodb through the standard node driver. /// Will get the URL for the mongodb from the global config `app-config.ts`. import { MongoClient, Collection, ObjectID } from 'mongodb'; import { APP_CONFIG } from '../app-config'; /** * Promise will resolve to the db. */ const DB_PROMISE = MongoClient.connect(APP_CONFIG.db.url); /** * Get a mongodb collection with no wrappers other than the driver itself. * * @param collectionName Name of the collection. * @returns Promise to the collection */ export const collection = (collectionName: string): Promise<Collection> => { return new Promise((resolve, reject) => { DB_PROMISE .then((db) => { resolve(db.collection(collectionName)); return; }) .catch((error) => { reject(error); return; }) });
* @param idString The id as a string * @returns A new mongo ObjectID object with idString as the ID */ export const ID = (idString: string): ObjectID => { return new ObjectID(idString); }
} /** * Get the ObjectID from an ID, basic convenience method. *
random_line_split
test.array.js
/* global describe, it, require */ 'use strict'; // MODULES // var // Expectation library: chai = require( 'chai' ), // Deep close to: deepCloseTo = require( './utils/deepcloseto.js' ), // Module to be tested:
// VARIABLES // var expect = chai.expect, assert = chai.assert; // TESTS // describe( 'array log10', function tests() { it( 'should export a function', function test() { expect( log10 ).to.be.a( 'function' ); }); it( 'should compute the base-10 logarithm', function test() { var data, actual, expected; data = [ Math.pow( 10, 4 ), Math.pow( 10, 6 ), Math.pow( 10, 9 ), Math.pow( 10, 15 ), Math.pow( 10, 10 ), Math.pow( 10, 25 ) ]; actual = new Array( data.length ); actual = log10( actual, data ); expected = [ 4, 6, 9, 15, 10, 25 ]; assert.isTrue( deepCloseTo( actual, expected, 1e-7 ) ); }); it( 'should return an empty array if provided an empty array', function test() { assert.deepEqual( log10( [], [] ), [] ); }); it( 'should handle non-numeric values by setting the element to NaN', function test() { var data, actual, expected; data = [ true, null, [], {} ]; actual = new Array( data.length ); actual = log10( actual, data ); expected = [ NaN, NaN, NaN, NaN ]; assert.deepEqual( actual, expected ); }); });
log10 = require( './../lib/array.js' );
random_line_split
iso_8859_9.rs
pub fn charmap() -> [&'static str, .. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13 "\x14", // 0x14 "\x15", // 0x15 "\x16", // 0x16 "\x17", // 0x17 "\x18", // 0x18 "\x19", // 0x19 "\x1a", // 0x1a "\x1b", // 0x1b "\x1c", // 0x1c "\x1d", // 0x1d "\x1e", // 0x1e "\x1f", // 0x1f " ", // 0x20 "!", // 0x21 "\"", // 0x22 "#", // 0x23 "$", // 0x24 "%", // 0x25 "&", // 0x26 "'", // 0x27 "(", // 0x28 ")", // 0x29 "*", // 0x2a "+", // 0x2b ",", // 0x2c "-", // 0x2d ".", // 0x2e "/", // 0x2f "0", // 0x30 "1", // 0x31 "2", // 0x32 "3", // 0x33 "4", // 0x34 "5", // 0x35 "6", // 0x36 "7", // 0x37 "8", // 0x38 "9", // 0x39 ":", // 0x3a ";", // 0x3b "<", // 0x3c "=", // 0x3d ">", // 0x3e "?", // 0x3f "@", // 0x40 "A", // 0x41 "B", // 0x42 "C", // 0x43 "D", // 0x44 "E", // 0x45 "F", // 0x46 "G", // 0x47 "H", // 0x48 "I", // 0x49 "J", // 0x4a "K", // 0x4b "L", // 0x4c "M", // 0x4d "N", // 0x4e "O", // 0x4f "P", // 0x50 "Q", // 0x51 "R", // 0x52 "S", // 0x53 "T", // 0x54 "U", // 0x55 "V", // 0x56 "W", // 0x57 "X", // 0x58 "Y", // 0x59 "Z", // 0x5a "[", // 0x5b "\\", // 0x5c "]", // 0x5d "^", // 0x5e "_", // 0x5f "`", // 0x60 "a", // 0x61 "b", // 0x62 "c", // 0x63 "d", // 0x64 "e", // 0x65 "f", // 0x66 "g", // 0x67 "h", // 0x68 "i", // 0x69 "j", // 0x6a "k", // 0x6b "l", // 0x6c "m", // 0x6d "n", // 0x6e "o", // 0x6f "p", // 0x70 "q", // 0x71 "r", // 0x72 "s", // 0x73 "t", // 0x74 "u", // 0x75 "v", // 0x76 "w", // 0x77 "x", // 0x78 "y", // 0x79 "z", // 0x7a "{", // 0x7b "|", // 0x7c "}", // 0x7d "~", // 0x7e "\x7f", // 0x7f "\x80", // 0x80 "\x81", // 0x81 "\x82", // 0x82 "\x83", // 0x83 "\x84", // 0x84 "\x85", // 0x85 "\x86", // 0x86 "\x87", // 0x87 "\x88", // 0x88 "\x89", // 0x89 "\x8a", // 0x8a "\x8b", // 0x8b "\x8c", // 0x8c "\x8d", // 0x8d "\x8e", // 0x8e "\x8f", // 0x8f "\x90", // 0x90 "\x91", // 0x91 "\x92", // 0x92 "\x93", // 0x93 "\x94", // 0x94 "\x95", // 0x95 "\x96", // 0x96 "\x97", // 0x97 "\x98", // 0x98 "\x99", // 0x99 "\x9a", // 0x9a "\x9b", // 0x9b "\x9c", // 0x9c "\x9d", // 0x9d "\x9e", // 0x9e "\x9f", // 0x9f "\xa0", // 0xa0 "\xa1", // 0xa1 "\xa2", // 0xa2 "\xa3", // 0xa3 "\xa4", // 0xa4 "\xa5", // 0xa5 "\xa6", // 0xa6 "\xa7", // 0xa7 "\xa8", // 0xa8 "\xa9", // 0xa9 "\xaa", // 0xaa "\xab", // 0xab "\xac", // 0xac "\xad", // 0xad "\xae", // 0xae "\xaf", // 0xaf "\xb0", // 0xb0 "\xb1", // 0xb1 "\xb2", // 0xb2 "\xb3", // 0xb3 "\xb4", // 0xb4 "\xb5", // 0xb5 "\xb6", // 0xb6 "\xb7", // 0xb7 "\xb8", // 0xb8 "\xb9", // 0xb9 "\xba", // 0xba "\xbb", // 0xbb "\xbc", // 0xbc "\xbd", // 0xbd "\xbe", // 0xbe "\xbf", // 0xbf "\xc0", // 0xc0 "\xc1", // 0xc1 "\xc2", // 0xc2 "\xc3", // 0xc3 "\xc4", // 0xc4 "\xc5", // 0xc5 "\xc6", // 0xc6
"\xcb", // 0xcb "\xcc", // 0xcc "\xcd", // 0xcd "\xce", // 0xce "\xcf", // 0xcf "\u011e", // 0xd0 "\xd1", // 0xd1 "\xd2", // 0xd2 "\xd3", // 0xd3 "\xd4", // 0xd4 "\xd5", // 0xd5 "\xd6", // 0xd6 "\xd7", // 0xd7 "\xd8", // 0xd8 "\xd9", // 0xd9 "\xda", // 0xda "\xdb", // 0xdb "\xdc", // 0xdc "\u0130", // 0xdd "\u015e", // 0xde "\xdf", // 0xdf "\xe0", // 0xe0 "\xe1", // 0xe1 "\xe2", // 0xe2 "\xe3", // 0xe3 "\xe4", // 0xe4 "\xe5", // 0xe5 "\xe6", // 0xe6 "\xe7", // 0xe7 "\xe8", // 0xe8 "\xe9", // 0xe9 "\xea", // 0xea "\xeb", // 0xeb "\xec", // 0xec "\xed", // 0xed "\xee", // 0xee "\xef", // 0xef "\u011f", // 0xf0 "\xf1", // 0xf1 "\xf2", // 0xf2 "\xf3", // 0xf3 "\xf4", // 0xf4 "\xf5", // 0xf5 "\xf6", // 0xf6 "\xf7", // 0xf7 "\xf8", // 0xf8 "\xf9", // 0xf9 "\xfa", // 0xfa "\xfb", // 0xfb "\xfc", // 0xfc "\u0131", // 0xfd "\u015f", // 0xfe "\xff", // 0xff ];}
"\xc7", // 0xc7 "\xc8", // 0xc8 "\xc9", // 0xc9 "\xca", // 0xca
random_line_split
iso_8859_9.rs
pub fn
() -> [&'static str, .. 256]{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13 "\x14", // 0x14 "\x15", // 0x15 "\x16", // 0x16 "\x17", // 0x17 "\x18", // 0x18 "\x19", // 0x19 "\x1a", // 0x1a "\x1b", // 0x1b "\x1c", // 0x1c "\x1d", // 0x1d "\x1e", // 0x1e "\x1f", // 0x1f " ", // 0x20 "!", // 0x21 "\"", // 0x22 "#", // 0x23 "$", // 0x24 "%", // 0x25 "&", // 0x26 "'", // 0x27 "(", // 0x28 ")", // 0x29 "*", // 0x2a "+", // 0x2b ",", // 0x2c "-", // 0x2d ".", // 0x2e "/", // 0x2f "0", // 0x30 "1", // 0x31 "2", // 0x32 "3", // 0x33 "4", // 0x34 "5", // 0x35 "6", // 0x36 "7", // 0x37 "8", // 0x38 "9", // 0x39 ":", // 0x3a ";", // 0x3b "<", // 0x3c "=", // 0x3d ">", // 0x3e "?", // 0x3f "@", // 0x40 "A", // 0x41 "B", // 0x42 "C", // 0x43 "D", // 0x44 "E", // 0x45 "F", // 0x46 "G", // 0x47 "H", // 0x48 "I", // 0x49 "J", // 0x4a "K", // 0x4b "L", // 0x4c "M", // 0x4d "N", // 0x4e "O", // 0x4f "P", // 0x50 "Q", // 0x51 "R", // 0x52 "S", // 0x53 "T", // 0x54 "U", // 0x55 "V", // 0x56 "W", // 0x57 "X", // 0x58 "Y", // 0x59 "Z", // 0x5a "[", // 0x5b "\\", // 0x5c "]", // 0x5d "^", // 0x5e "_", // 0x5f "`", // 0x60 "a", // 0x61 "b", // 0x62 "c", // 0x63 "d", // 0x64 "e", // 0x65 "f", // 0x66 "g", // 0x67 "h", // 0x68 "i", // 0x69 "j", // 0x6a "k", // 0x6b "l", // 0x6c "m", // 0x6d "n", // 0x6e "o", // 0x6f "p", // 0x70 "q", // 0x71 "r", // 0x72 "s", // 0x73 "t", // 0x74 "u", // 0x75 "v", // 0x76 "w", // 0x77 "x", // 0x78 "y", // 0x79 "z", // 0x7a "{", // 0x7b "|", // 0x7c "}", // 0x7d "~", // 0x7e "\x7f", // 0x7f "\x80", // 0x80 "\x81", // 0x81 "\x82", // 0x82 "\x83", // 0x83 "\x84", // 0x84 "\x85", // 0x85 "\x86", // 0x86 "\x87", // 0x87 "\x88", // 0x88 "\x89", // 0x89 "\x8a", // 0x8a "\x8b", // 0x8b "\x8c", // 0x8c "\x8d", // 0x8d "\x8e", // 0x8e "\x8f", // 0x8f "\x90", // 0x90 "\x91", // 0x91 "\x92", // 0x92 "\x93", // 0x93 "\x94", // 0x94 "\x95", // 0x95 "\x96", // 0x96 "\x97", // 0x97 "\x98", // 0x98 "\x99", // 0x99 "\x9a", // 0x9a "\x9b", // 0x9b "\x9c", // 0x9c "\x9d", // 0x9d "\x9e", // 0x9e "\x9f", // 0x9f "\xa0", // 0xa0 "\xa1", // 0xa1 "\xa2", // 0xa2 "\xa3", // 0xa3 "\xa4", // 0xa4 "\xa5", // 0xa5 "\xa6", // 0xa6 "\xa7", // 0xa7 "\xa8", // 0xa8 "\xa9", // 0xa9 "\xaa", // 0xaa "\xab", // 0xab "\xac", // 0xac "\xad", // 0xad "\xae", // 0xae "\xaf", // 0xaf "\xb0", // 0xb0 "\xb1", // 0xb1 "\xb2", // 0xb2 "\xb3", // 0xb3 "\xb4", // 0xb4 "\xb5", // 0xb5 "\xb6", // 0xb6 "\xb7", // 0xb7 "\xb8", // 0xb8 "\xb9", // 0xb9 "\xba", // 0xba "\xbb", // 0xbb "\xbc", // 0xbc "\xbd", // 0xbd "\xbe", // 0xbe "\xbf", // 0xbf "\xc0", // 0xc0 "\xc1", // 0xc1 "\xc2", // 0xc2 "\xc3", // 0xc3 "\xc4", // 0xc4 "\xc5", // 0xc5 "\xc6", // 0xc6 "\xc7", // 0xc7 "\xc8", // 0xc8 "\xc9", // 0xc9 "\xca", // 0xca "\xcb", // 0xcb "\xcc", // 0xcc "\xcd", // 0xcd "\xce", // 0xce "\xcf", // 0xcf "\u011e", // 0xd0 "\xd1", // 0xd1 "\xd2", // 0xd2 "\xd3", // 0xd3 "\xd4", // 0xd4 "\xd5", // 0xd5 "\xd6", // 0xd6 "\xd7", // 0xd7 "\xd8", // 0xd8 "\xd9", // 0xd9 "\xda", // 0xda "\xdb", // 0xdb "\xdc", // 0xdc "\u0130", // 0xdd "\u015e", // 0xde "\xdf", // 0xdf "\xe0", // 0xe0 "\xe1", // 0xe1 "\xe2", // 0xe2 "\xe3", // 0xe3 "\xe4", // 0xe4 "\xe5", // 0xe5 "\xe6", // 0xe6 "\xe7", // 0xe7 "\xe8", // 0xe8 "\xe9", // 0xe9 "\xea", // 0xea "\xeb", // 0xeb "\xec", // 0xec "\xed", // 0xed "\xee", // 0xee "\xef", // 0xef "\u011f", // 0xf0 "\xf1", // 0xf1 "\xf2", // 0xf2 "\xf3", // 0xf3 "\xf4", // 0xf4 "\xf5", // 0xf5 "\xf6", // 0xf6 "\xf7", // 0xf7 "\xf8", // 0xf8 "\xf9", // 0xf9 "\xfa", // 0xfa "\xfb", // 0xfb "\xfc", // 0xfc "\u0131", // 0xfd "\u015f", // 0xfe "\xff", // 0xff ];}
charmap
identifier_name
iso_8859_9.rs
pub fn charmap() -> [&'static str, .. 256]
{ return ["\x00", // 0x0 "\x01", // 0x1 "\x02", // 0x2 "\x03", // 0x3 "\x04", // 0x4 "\x05", // 0x5 "\x06", // 0x6 "\x07", // 0x7 "\x08", // 0x8 "\t", // 0x9 "\n", // 0xa "\x0b", // 0xb "\x0c", // 0xc "\r", // 0xd "\x0e", // 0xe "\x0f", // 0xf "\x10", // 0x10 "\x11", // 0x11 "\x12", // 0x12 "\x13", // 0x13 "\x14", // 0x14 "\x15", // 0x15 "\x16", // 0x16 "\x17", // 0x17 "\x18", // 0x18 "\x19", // 0x19 "\x1a", // 0x1a "\x1b", // 0x1b "\x1c", // 0x1c "\x1d", // 0x1d "\x1e", // 0x1e "\x1f", // 0x1f " ", // 0x20 "!", // 0x21 "\"", // 0x22 "#", // 0x23 "$", // 0x24 "%", // 0x25 "&", // 0x26 "'", // 0x27 "(", // 0x28 ")", // 0x29 "*", // 0x2a "+", // 0x2b ",", // 0x2c "-", // 0x2d ".", // 0x2e "/", // 0x2f "0", // 0x30 "1", // 0x31 "2", // 0x32 "3", // 0x33 "4", // 0x34 "5", // 0x35 "6", // 0x36 "7", // 0x37 "8", // 0x38 "9", // 0x39 ":", // 0x3a ";", // 0x3b "<", // 0x3c "=", // 0x3d ">", // 0x3e "?", // 0x3f "@", // 0x40 "A", // 0x41 "B", // 0x42 "C", // 0x43 "D", // 0x44 "E", // 0x45 "F", // 0x46 "G", // 0x47 "H", // 0x48 "I", // 0x49 "J", // 0x4a "K", // 0x4b "L", // 0x4c "M", // 0x4d "N", // 0x4e "O", // 0x4f "P", // 0x50 "Q", // 0x51 "R", // 0x52 "S", // 0x53 "T", // 0x54 "U", // 0x55 "V", // 0x56 "W", // 0x57 "X", // 0x58 "Y", // 0x59 "Z", // 0x5a "[", // 0x5b "\\", // 0x5c "]", // 0x5d "^", // 0x5e "_", // 0x5f "`", // 0x60 "a", // 0x61 "b", // 0x62 "c", // 0x63 "d", // 0x64 "e", // 0x65 "f", // 0x66 "g", // 0x67 "h", // 0x68 "i", // 0x69 "j", // 0x6a "k", // 0x6b "l", // 0x6c "m", // 0x6d "n", // 0x6e "o", // 0x6f "p", // 0x70 "q", // 0x71 "r", // 0x72 "s", // 0x73 "t", // 0x74 "u", // 0x75 "v", // 0x76 "w", // 0x77 "x", // 0x78 "y", // 0x79 "z", // 0x7a "{", // 0x7b "|", // 0x7c "}", // 0x7d "~", // 0x7e "\x7f", // 0x7f "\x80", // 0x80 "\x81", // 0x81 "\x82", // 0x82 "\x83", // 0x83 "\x84", // 0x84 "\x85", // 0x85 "\x86", // 0x86 "\x87", // 0x87 "\x88", // 0x88 "\x89", // 0x89 "\x8a", // 0x8a "\x8b", // 0x8b "\x8c", // 0x8c "\x8d", // 0x8d "\x8e", // 0x8e "\x8f", // 0x8f "\x90", // 0x90 "\x91", // 0x91 "\x92", // 0x92 "\x93", // 0x93 "\x94", // 0x94 "\x95", // 0x95 "\x96", // 0x96 "\x97", // 0x97 "\x98", // 0x98 "\x99", // 0x99 "\x9a", // 0x9a "\x9b", // 0x9b "\x9c", // 0x9c "\x9d", // 0x9d "\x9e", // 0x9e "\x9f", // 0x9f "\xa0", // 0xa0 "\xa1", // 0xa1 "\xa2", // 0xa2 "\xa3", // 0xa3 "\xa4", // 0xa4 "\xa5", // 0xa5 "\xa6", // 0xa6 "\xa7", // 0xa7 "\xa8", // 0xa8 "\xa9", // 0xa9 "\xaa", // 0xaa "\xab", // 0xab "\xac", // 0xac "\xad", // 0xad "\xae", // 0xae "\xaf", // 0xaf "\xb0", // 0xb0 "\xb1", // 0xb1 "\xb2", // 0xb2 "\xb3", // 0xb3 "\xb4", // 0xb4 "\xb5", // 0xb5 "\xb6", // 0xb6 "\xb7", // 0xb7 "\xb8", // 0xb8 "\xb9", // 0xb9 "\xba", // 0xba "\xbb", // 0xbb "\xbc", // 0xbc "\xbd", // 0xbd "\xbe", // 0xbe "\xbf", // 0xbf "\xc0", // 0xc0 "\xc1", // 0xc1 "\xc2", // 0xc2 "\xc3", // 0xc3 "\xc4", // 0xc4 "\xc5", // 0xc5 "\xc6", // 0xc6 "\xc7", // 0xc7 "\xc8", // 0xc8 "\xc9", // 0xc9 "\xca", // 0xca "\xcb", // 0xcb "\xcc", // 0xcc "\xcd", // 0xcd "\xce", // 0xce "\xcf", // 0xcf "\u011e", // 0xd0 "\xd1", // 0xd1 "\xd2", // 0xd2 "\xd3", // 0xd3 "\xd4", // 0xd4 "\xd5", // 0xd5 "\xd6", // 0xd6 "\xd7", // 0xd7 "\xd8", // 0xd8 "\xd9", // 0xd9 "\xda", // 0xda "\xdb", // 0xdb "\xdc", // 0xdc "\u0130", // 0xdd "\u015e", // 0xde "\xdf", // 0xdf "\xe0", // 0xe0 "\xe1", // 0xe1 "\xe2", // 0xe2 "\xe3", // 0xe3 "\xe4", // 0xe4 "\xe5", // 0xe5 "\xe6", // 0xe6 "\xe7", // 0xe7 "\xe8", // 0xe8 "\xe9", // 0xe9 "\xea", // 0xea "\xeb", // 0xeb "\xec", // 0xec "\xed", // 0xed "\xee", // 0xee "\xef", // 0xef "\u011f", // 0xf0 "\xf1", // 0xf1 "\xf2", // 0xf2 "\xf3", // 0xf3 "\xf4", // 0xf4 "\xf5", // 0xf5 "\xf6", // 0xf6 "\xf7", // 0xf7 "\xf8", // 0xf8 "\xf9", // 0xf9 "\xfa", // 0xfa "\xfb", // 0xfb "\xfc", // 0xfc "\u0131", // 0xfd "\u015f", // 0xfe "\xff", // 0xff ];}
identifier_body
angular-route.js
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @license AngularJS v1.2.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc overview * @name ngRoute * @description * * # ngRoute * * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * {@installModule route} * * <div doc-module-components="ngRoute"></div> */ /* global -ngRouteModule */ var ngRouteModule = angular.module('ngRoute', ['ng']). provider('$route', $RouteProvider); /** * @ngdoc object * @name ngRoute.$routeProvider * @function * * @description * * Used for configuring routes. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ function $RouteProvider(){ function inherit(parent, extra) { return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); } var routes = {}; /** * @ngdoc method * @name ngRoute.$routeProvider#when * @methodOf ngRoute.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a colon and ending with a star: * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain optional named groups with a question mark: e.g.`:name?`. * * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object * is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` * or `$location.hash()` changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = angular.extend( {reloadOnSearch: true}, route, path && pathRegExp(path, route) ); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = angular.extend( {redirectTo: path}, pathRegExp(redirectPath, route) ); } return this; }; /** * @param path {string} path * @param opts {Object} options * @return {?Object} * * @description * Normalizes the given path, returning a regular expression * and the original path. * * Inspired by pathRexp in visionmedia/express/lib/utils.js. */ function pathRegExp(path, opts) { var insensitive = opts.caseInsensitiveMatch, ret = { originalPath: path, regexp: path }, keys = ret.keys = []; path = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([\/$\*])/g, '\\$1'); ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); return ret; } /** * @ngdoc method * @name ngRoute.$routeProvider#otherwise * @methodOf ngRoute.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', '$sce', function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { /** * @ngdoc object * @name ngRoute.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * `$route` is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with the * {@link ngRoute.directive:ngView `ngView`} directive and the * {@link ngRoute.$routeParams `$routeParams`} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngViewExample" deps="angular-route.js"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute']) .config(function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /**
* @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occur. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeSuccess * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is * first route entered. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeError * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ngRoute.$route#$routeUpdate * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ngRoute.$route#reload * @methodOf ngRoute.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param route {Object} route regexp to match the url against * @return {?Object} * * @description * Check if the route matches the current url. * * Inspired by match in * visionmedia/express/lib/router/router.js. */ function switchRouteMatcher(on, route) { var keys = route.keys, params = {}; if (!route.regexp) return null; var m = route.regexp.exec(on); if (!m) return null; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = 'string' == typeof m[i] ? decodeURIComponent(m[i]) : m[i]; if (key && val) { params[key.name] = val; } } return params; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && angular.equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; angular.copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (angular.isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = angular.extend({}, next.resolve), template, templateUrl; angular.forEach(locals, function(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (angular.isDefined(template = next.template)) { if (angular.isFunction(template)) { template = template(next.params); } } else if (angular.isDefined(templateUrl = next.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(next.params); } templateUrl = $sce.getTrustedResourceUrl(templateUrl); if (angular.isDefined(templateUrl)) { next.loadedTemplateUrl = templateUrl; template = $http.get(templateUrl, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; angular.copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; angular.forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), route))) { match = inherit(route, { params: angular.extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; angular.forEach((string||'').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } ngRouteModule.provider('$routeParams', $RouteParamsProvider); /** * @ngdoc object * @name ngRoute.$routeParams * @requires $route * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * The route parameters are a combination of {@link ng.$location `$location`}'s * {@link ng.$location#methods_search `search()`} and {@link ng.$location#methods_path `path()`}. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * Note that the `$routeParams` are only updated *after* a route change completes successfully. * This means that you cannot rely on `$routeParams` being correct in route resolve functions. * Instead you can use `$route.current.params` to access the new route's parameters. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = function() { return {}; }; } ngRouteModule.directive('ngView', ngViewFactory); ngRouteModule.directive('ngView', ngViewFillContentFactory); /** * @ngdoc directive * @name ngRoute.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * @param {string=} onload Expression to evaluate whenever the view updates. * * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated * as an expression yields a truthy value. * @example <example module="ngViewExample" deps="angular-route.js" animations="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div class="view-animate-container"> <div ng-view class="view-animate"></div> </div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .view-animate-container { position:relative; height:100px!important; position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .view-animate { padding:10px; } .view-animate.ng-enter, .view-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .view-animate.ng-enter { left:100%; } .view-animate.ng-enter.ng-enter-active { left:0; } .view-animate.ng-leave.ng-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.directive:ngView#$viewContentLoaded * @eventOf ngRoute.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; function ngViewFactory( $route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function cleanupLastView() { if (currentScope) { currentScope.$destroy(); currentScope = null; } if(currentElement) { $animate.leave(currentElement); currentElement = null; } } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { var newScope = scope.$new(); var current = $route.current; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentElement = clone; currentScope = current.scope = newScope; currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } else { cleanupLastView(); } } } }; } // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; function ngViewFillContentFactory($compile, $controller, $route) { return { restrict: 'ECA', priority: -400, link: function(scope, $element) { var current = $route.current, locals = current.locals; $element.html(locals.$template); var link = $compile($element.contents()); if (current.controller) { locals.$scope = scope; var controller = $controller(current.controller, locals); if (current.controllerAs) { scope[current.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); } }; } })(window, window.angular);
* @ngdoc event * @name ngRoute.$route#$routeChangeStart
random_line_split
angular-route.js
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @license AngularJS v1.2.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc overview * @name ngRoute * @description * * # ngRoute * * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * {@installModule route} * * <div doc-module-components="ngRoute"></div> */ /* global -ngRouteModule */ var ngRouteModule = angular.module('ngRoute', ['ng']). provider('$route', $RouteProvider); /** * @ngdoc object * @name ngRoute.$routeProvider * @function * * @description * * Used for configuring routes. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ function $RouteProvider(){ function inherit(parent, extra) { return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); } var routes = {}; /** * @ngdoc method * @name ngRoute.$routeProvider#when * @methodOf ngRoute.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a colon and ending with a star: * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain optional named groups with a question mark: e.g.`:name?`. * * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object * is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` * or `$location.hash()` changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = angular.extend( {reloadOnSearch: true}, route, path && pathRegExp(path, route) ); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = angular.extend( {redirectTo: path}, pathRegExp(redirectPath, route) ); } return this; }; /** * @param path {string} path * @param opts {Object} options * @return {?Object} * * @description * Normalizes the given path, returning a regular expression * and the original path. * * Inspired by pathRexp in visionmedia/express/lib/utils.js. */ function pathRegExp(path, opts) { var insensitive = opts.caseInsensitiveMatch, ret = { originalPath: path, regexp: path }, keys = ret.keys = []; path = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([\/$\*])/g, '\\$1'); ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); return ret; } /** * @ngdoc method * @name ngRoute.$routeProvider#otherwise * @methodOf ngRoute.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', '$sce', function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { /** * @ngdoc object * @name ngRoute.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * `$route` is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with the * {@link ngRoute.directive:ngView `ngView`} directive and the * {@link ngRoute.$routeParams `$routeParams`} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngViewExample" deps="angular-route.js"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute']) .config(function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeStart * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occur. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeSuccess * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is * first route entered. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeError * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ngRoute.$route#$routeUpdate * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ngRoute.$route#reload * @methodOf ngRoute.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param route {Object} route regexp to match the url against * @return {?Object} * * @description * Check if the route matches the current url. * * Inspired by match in * visionmedia/express/lib/router/router.js. */ function switchRouteMatcher(on, route) { var keys = route.keys, params = {}; if (!route.regexp) return null; var m = route.regexp.exec(on); if (!m) return null; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = 'string' == typeof m[i] ? decodeURIComponent(m[i]) : m[i]; if (key && val) { params[key.name] = val; } } return params; } function updateRoute() { var next = par
urns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; angular.forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), route))) { match = inherit(route, { params: angular.extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; angular.forEach((string||'').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } ngRouteModule.provider('$routeParams', $RouteParamsProvider); /** * @ngdoc object * @name ngRoute.$routeParams * @requires $route * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * The route parameters are a combination of {@link ng.$location `$location`}'s * {@link ng.$location#methods_search `search()`} and {@link ng.$location#methods_path `path()`}. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * Note that the `$routeParams` are only updated *after* a route change completes successfully. * This means that you cannot rely on `$routeParams` being correct in route resolve functions. * Instead you can use `$route.current.params` to access the new route's parameters. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = function() { return {}; }; } ngRouteModule.directive('ngView', ngViewFactory); ngRouteModule.directive('ngView', ngViewFillContentFactory); /** * @ngdoc directive * @name ngRoute.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * @param {string=} onload Expression to evaluate whenever the view updates. * * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated * as an expression yields a truthy value. * @example <example module="ngViewExample" deps="angular-route.js" animations="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div class="view-animate-container"> <div ng-view class="view-animate"></div> </div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .view-animate-container { position:relative; height:100px!important; position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .view-animate { padding:10px; } .view-animate.ng-enter, .view-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .view-animate.ng-enter { left:100%; } .view-animate.ng-enter.ng-enter-active { left:0; } .view-animate.ng-leave.ng-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.directive:ngView#$viewContentLoaded * @eventOf ngRoute.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; function ngViewFactory( $route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function cleanupLastView() { if (currentScope) { currentScope.$destroy(); currentScope = null; } if(currentElement) { $animate.leave(currentElement); currentElement = null; } } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { var newScope = scope.$new(); var current = $route.current; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentElement = clone; currentScope = current.scope = newScope; currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } else { cleanupLastView(); } } } }; } // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; function ngViewFillContentFactory($compile, $controller, $route) { return { restrict: 'ECA', priority: -400, link: function(scope, $element) { var current = $route.current, locals = current.locals; $element.html(locals.$template); var link = $compile($element.contents()); if (current.controller) { locals.$scope = scope; var controller = $controller(current.controller, locals); if (current.controllerAs) { scope[current.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); } }; } })(window, window.angular);
seRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && angular.equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; angular.copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (angular.isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = angular.extend({}, next.resolve), template, templateUrl; angular.forEach(locals, function(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (angular.isDefined(template = next.template)) { if (angular.isFunction(template)) { template = template(next.params); } } else if (angular.isDefined(templateUrl = next.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(next.params); } templateUrl = $sce.getTrustedResourceUrl(templateUrl); if (angular.isDefined(templateUrl)) { next.loadedTemplateUrl = templateUrl; template = $http.get(templateUrl, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; angular.copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @ret
identifier_body
angular-route.js
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @license AngularJS v1.2.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc overview * @name ngRoute * @description * * # ngRoute * * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * {@installModule route} * * <div doc-module-components="ngRoute"></div> */ /* global -ngRouteModule */ var ngRouteModule = angular.module('ngRoute', ['ng']). provider('$route', $RouteProvider); /** * @ngdoc object * @name ngRoute.$routeProvider * @function * * @description * * Used for configuring routes. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ function $RouteProvider(){ function inherit(parent, extra) { return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); } var routes = {}; /** * @ngdoc method * @name ngRoute.$routeProvider#when * @methodOf ngRoute.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a colon and ending with a star: * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain optional named groups with a question mark: e.g.`:name?`. * * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object * is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` * or `$location.hash()` changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = angular.extend( {reloadOnSearch: true}, route, path && pathRegExp(path, route) ); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = angular.extend( {redirectTo: path}, pathRegExp(redirectPath, route) ); } return this; }; /** * @param path {string} path * @param opts {Object} options * @return {?Object} * * @description * Normalizes the given path, returning a regular expression * and the original path. * * Inspired by pathRexp in visionmedia/express/lib/utils.js. */ function pathRegExp(path, opts) { var insensitive = opts.caseInsensitiveMatch, ret = { originalPath: path, regexp: path }, keys = ret.keys = []; path = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([\/$\*])/g, '\\$1'); ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); return ret; } /** * @ngdoc method * @name ngRoute.$routeProvider#otherwise * @methodOf ngRoute.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', '$sce', function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { /** * @ngdoc object * @name ngRoute.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * `$route` is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with the * {@link ngRoute.directive:ngView `ngView`} directive and the * {@link ngRoute.$routeParams `$routeParams`} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngViewExample" deps="angular-route.js"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute']) .config(function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeStart * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occur. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeSuccess * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is * first route entered. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeError * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ngRoute.$route#$routeUpdate * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ngRoute.$route#reload * @methodOf ngRoute.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param route {Object} route regexp to match the url against * @return {?Object} * * @description * Check if the route matches the current url. * * Inspired by match in * visionmedia/express/lib/router/router.js. */ function switchRouteMatcher(on, route) { var keys = route.keys, params = {}; if (!route.regexp) return null; var m = route.regexp.exec(on); if (!m) return null; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = 'string' == typeof m[i] ? decodeURIComponent(m[i]) : m[i]; if (key && val) { params[key.name] = val; } } return params; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && angular.equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; angular.copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (angular.isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = angular.extend({}, next.resolve), template, templateUrl; angular.forEach(locals, function(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (angular.isDefined(template = next.template)) { if (angular.isFunction(template)) { template = template(next.params); } } else if (angular.isDefined(templateUrl = next.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(next.params); } templateUrl = $sce.getTrustedResourceUrl(templateUrl); if (angular.isDefined(templateUrl)) { next.loadedTemplateUrl = templateUrl; template = $http.get(templateUrl, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; angular.copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; angular.forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), route))) { match = inherit(route, { params: angular.extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; angular.forEach((string||'').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } ngRouteModule.provider('$routeParams', $RouteParamsProvider); /** * @ngdoc object * @name ngRoute.$routeParams * @requires $route * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * The route parameters are a combination of {@link ng.$location `$location`}'s * {@link ng.$location#methods_search `search()`} and {@link ng.$location#methods_path `path()`}. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * Note that the `$routeParams` are only updated *after* a route change completes successfully. * This means that you cannot rely on `$routeParams` being correct in route resolve functions. * Instead you can use `$route.current.params` to access the new route's parameters. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = function() { return {}; }; } ngRouteModule.directive('ngView', ngViewFactory); ngRouteModule.directive('ngView', ngViewFillContentFactory); /** * @ngdoc directive * @name ngRoute.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * @param {string=} onload Expression to evaluate whenever the view updates. * * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated * as an expression yields a truthy value. * @example <example module="ngViewExample" deps="angular-route.js" animations="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div class="view-animate-container"> <div ng-view class="view-animate"></div> </div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .view-animate-container { position:relative; height:100px!important; position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .view-animate { padding:10px; } .view-animate.ng-enter, .view-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .view-animate.ng-enter { left:100%; } .view-animate.ng-enter.ng-enter-active { left:0; } .view-animate.ng-leave.ng-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.directive:ngView#$viewContentLoaded * @eventOf ngRoute.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; function ngViewFactory( $route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function cleanupLastView() { if (currentScope) { currentScope.$destroy(); currentScope = null; } if(currentElement) { $animate.leave(currentElement); currentElement = null; } } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { var newScope = scope.$new(); var current = $route.current; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentElement = clone; currentScope = current.scope = newScope; currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } else { cleanupLastView(); } } } }; } // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; function ngViewFillContentFacto
, $route) { return { restrict: 'ECA', priority: -400, link: function(scope, $element) { var current = $route.current, locals = current.locals; $element.html(locals.$template); var link = $compile($element.contents()); if (current.controller) { locals.$scope = scope; var controller = $controller(current.controller, locals); if (current.controllerAs) { scope[current.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); } }; } })(window, window.angular);
ry($compile, $controller
identifier_name
angular-route.js
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @license AngularJS v1.2.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc overview * @name ngRoute * @description * * # ngRoute * * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * {@installModule route} * * <div doc-module-components="ngRoute"></div> */ /* global -ngRouteModule */ var ngRouteModule = angular.module('ngRoute', ['ng']). provider('$route', $RouteProvider); /** * @ngdoc object * @name ngRoute.$routeProvider * @function * * @description * * Used for configuring routes. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ function $RouteProvider(){ function inherit(parent, extra) { return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); } var routes = {}; /** * @ngdoc method * @name ngRoute.$routeProvider#when * @methodOf ngRoute.$routeProvider * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a colon and ending with a star: * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain optional named groups with a question mark: e.g.`:name?`. * * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match * `/color/brown/largecode/code/with/slashs/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashs`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` – `{(string|function()=}` – Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. * - `controllerAs` – `{string=}` – A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` – `{string=|function()=}` – html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` – `{string=|function()=}` – path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.<Object>}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object * is: * * - `key` – `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * * - `redirectTo` – {(string|function())=} – value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` * or `$location.hash()` changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = angular.extend( {reloadOnSearch: true}, route, path && pathRegExp(path, route) ); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = angular.extend( {redirectTo: path}, pathRegExp(redirectPath, route) ); } return this; }; /** * @param path {string} path * @param opts {Object} options * @return {?Object} * * @description * Normalizes the given path, returning a regular expression * and the original path. * * Inspired by pathRexp in visionmedia/express/lib/utils.js. */ function pathRegExp(path, opts) { var insensitive = opts.caseInsensitiveMatch, ret = { originalPath: path, regexp: path }, keys = ret.keys = []; path = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([\/$\*])/g, '\\$1'); ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); return ret; } /** * @ngdoc method * @name ngRoute.$routeProvider#otherwise * @methodOf ngRoute.$routeProvider * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', '$sce', function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { /** * @ngdoc object * @name ngRoute.$route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.<Object>} routes Array of all configured routes. * * @description * `$route` is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with the * {@link ngRoute.directive:ngView `ngView`} directive and the * {@link ngRoute.$routeParams `$routeParams`} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example module="ngViewExample" deps="angular-route.js"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute']) .config(function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeStart * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occur. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeSuccess * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is * first route entered. */ /** * @ngdoc event * @name ngRoute.$route#$routeChangeError * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name ngRoute.$route#$routeUpdate * @eventOf ngRoute.$route * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name ngRoute.$route#reload * @methodOf ngRoute.$route * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param route {Object} route regexp to match the url against * @return {?Object} * * @description * Check if the route matches the current url. * * Inspired by match in * visionmedia/express/lib/router/router.js. */ function switchRouteMatcher(on, route) { var keys = route.keys, params = {}; if (!route.regexp) return null; var m = route.regexp.exec(on); if (!m) return null; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = 'string' == typeof m[i] ? decodeURIComponent(m[i]) : m[i]; if (key && val) { params[key.name] = val; } } return params; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && angular.equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; angular.copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (angular.isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = angular.extend({}, next.resolve), template, templateUrl; angular.forEach(locals, function(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (angular.isDefined(template = next.template)) { if (angular.isFunction(template)) { template = template(next.params); } } else if (angular.isDefined(templateUrl = next.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(next.params); } templateUrl = $sce.getTrustedResourceUrl(templateUrl); if (angular.isDefined(templateUrl)) { next.loadedTemplateUrl = templateUrl; template = $http.get(templateUrl, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; angular.copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; angular.forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), route))) { match = inherit(route, { params: angular.extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; angular.forEach((string||'').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } ngRouteModule.provider('$routeParams', $RouteParamsProvider); /** * @ngdoc object * @name ngRoute.$routeParams * @requires $route * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * The route parameters are a combination of {@link ng.$location `$location`}'s * {@link ng.$location#methods_search `search()`} and {@link ng.$location#methods_path `path()`}. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * Note that the `$routeParams` are only updated *after* a route change completes successfully. * This means that you cannot rely on `$routeParams` being correct in route resolve functions. * Instead you can use `$route.current.params` to access the new route's parameters. * * @example * <pre> * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * </pre> */ function $RouteParamsProvider() { this.$get = function() { return {}; }; } ngRouteModule.directive('ngView', ngViewFactory); ngRouteModule.directive('ngView', ngViewFillContentFactory); /** * @ngdoc directive * @name ngRoute.directive:ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * @param {string=} onload Expression to evaluate whenever the view updates. * * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated * as an expression yields a truthy value. * @example <example module="ngViewExample" deps="angular-route.js" animations="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div class="view-animate-container"> <div ng-view class="view-animate"></div> </div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .view-animate-container { position:relative; height:100px!important; position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .view-animate { padding:10px; } .view-animate.ng-enter, .view-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .view-animate.ng-enter { left:100%; } .view-animate.ng-enter.ng-enter-active { left:0; } .view-animate.ng-leave.ng-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="protractorTest.js"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('.doc-example-live [ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngRoute.directive:ngView#$viewContentLoaded * @eventOf ngRoute.directive:ngView * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; function ngViewFactory( $route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function cleanupLastView() { if (currentScope) { currentS
lement) { $animate.leave(currentElement); currentElement = null; } } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { var newScope = scope.$new(); var current = $route.current; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentElement = clone; currentScope = current.scope = newScope; currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } else { cleanupLastView(); } } } }; } // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; function ngViewFillContentFactory($compile, $controller, $route) { return { restrict: 'ECA', priority: -400, link: function(scope, $element) { var current = $route.current, locals = current.locals; $element.html(locals.$template); var link = $compile($element.contents()); if (current.controller) { locals.$scope = scope; var controller = $controller(current.controller, locals); if (current.controllerAs) { scope[current.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); } }; } })(window, window.angular);
cope.$destroy(); currentScope = null; } if(currentE
conditional_block
test_input.py
import numpy import pytest import theano class TestInputLayer: @pytest.fixture def layer(self): from lasagne.layers.input import InputLayer return InputLayer((3, 2)) def test_input_var(self, layer): assert layer.input_var.ndim == 2 def test_get_output_shape(self, layer): assert layer.get_output_shape() == (3, 2) def test_get_output_without_arguments(self, layer): assert layer.get_output() is layer.input_var
def test_get_output_input_is_variable(self, layer): variable = theano.Variable("myvariable") assert layer.get_output(variable) is variable def test_get_output_input_is_array(self, layer): input = [[1,2,3]] output = layer.get_output(input) assert numpy.all(output.eval() == input) def test_get_output_input_is_a_mapping(self, layer): input = {layer: theano.tensor.matrix()} assert layer.get_output(input) is input[layer] def test_input_var_name(self, layer): assert layer.input_var.name == "input" def test_named_layer_input_var_name(self): from lasagne.layers.input import InputLayer layer = InputLayer((3, 2), name="foo") assert layer.input_var.name == "foo.input"
random_line_split
test_input.py
import numpy import pytest import theano class TestInputLayer: @pytest.fixture def layer(self): from lasagne.layers.input import InputLayer return InputLayer((3, 2)) def test_input_var(self, layer): assert layer.input_var.ndim == 2 def
(self, layer): assert layer.get_output_shape() == (3, 2) def test_get_output_without_arguments(self, layer): assert layer.get_output() is layer.input_var def test_get_output_input_is_variable(self, layer): variable = theano.Variable("myvariable") assert layer.get_output(variable) is variable def test_get_output_input_is_array(self, layer): input = [[1,2,3]] output = layer.get_output(input) assert numpy.all(output.eval() == input) def test_get_output_input_is_a_mapping(self, layer): input = {layer: theano.tensor.matrix()} assert layer.get_output(input) is input[layer] def test_input_var_name(self, layer): assert layer.input_var.name == "input" def test_named_layer_input_var_name(self): from lasagne.layers.input import InputLayer layer = InputLayer((3, 2), name="foo") assert layer.input_var.name == "foo.input"
test_get_output_shape
identifier_name
test_input.py
import numpy import pytest import theano class TestInputLayer: @pytest.fixture def layer(self): from lasagne.layers.input import InputLayer return InputLayer((3, 2)) def test_input_var(self, layer): assert layer.input_var.ndim == 2 def test_get_output_shape(self, layer):
def test_get_output_without_arguments(self, layer): assert layer.get_output() is layer.input_var def test_get_output_input_is_variable(self, layer): variable = theano.Variable("myvariable") assert layer.get_output(variable) is variable def test_get_output_input_is_array(self, layer): input = [[1,2,3]] output = layer.get_output(input) assert numpy.all(output.eval() == input) def test_get_output_input_is_a_mapping(self, layer): input = {layer: theano.tensor.matrix()} assert layer.get_output(input) is input[layer] def test_input_var_name(self, layer): assert layer.input_var.name == "input" def test_named_layer_input_var_name(self): from lasagne.layers.input import InputLayer layer = InputLayer((3, 2), name="foo") assert layer.input_var.name == "foo.input"
assert layer.get_output_shape() == (3, 2)
identifier_body
diskImage.py
import devon.maker from devon.tags import * import datetime, os.path, shutil # ************************************************************************************************** class DiskImage(devon.maker.MakerManyToOne): path = "hdiutil" def getTarget(self, project): return "%s.dmg" % project.name def needsUpdate(self, project, target): return True def build(self, project, out, sources, target): bytes = 0.0 for source in sources: bytes += getDirectorySize(source) # Pad the rounding error a little, or we'll run out of space when copying megabytes = bytes/1000000 + 0.2 out << Block("progressBox progress-build") << "Creating disk image " \ << FileLink(path=target) << target << Close << "..." \ << Close # Create the disk image line = "%s create '%s' -megabytes %f -volname '%s' -fs HFS+" \ % (self.path, target, megabytes, project.name) result = devon.make.executeCommand(project, self, line, out) # Mount the disk image line = "%s attach '%s'" % (self.path, target) result = devon.make.executeCommand(project, self, line, out) # Copy each file to the disk image volumeName = "/Volumes/%s/" % project.name for source in sources: os.system("cp -R '%s' '%s'" % (source, volumeName)) # Unmount the disk image line = "%s detach '%s'" % (self.path, volumeName) result = devon.make.executeCommand(project, self, line, out) return result def printAction(self, project, out, target): out << Block("progressBox progress-build") << "Archiving " \ << FileLink(path=target) << target << Close << "..." \ << Close def printResult(self, project, out, text):
def __copyFile(self, source, destDir): if os.path.isdir(source): newDest = os.path.join(destDir, os.path.basename(source)) if not os.path.exists(newDest): os.makedirs(newDest) paths = os.listdir(source) for fileName in [name for name in paths if not name[0] == "."]: fileSource = os.path.join(source, fileName) self.__copyFile(fileSource, newDest) else: destPath = os.path.join(destDir, os.path.basename(source)) if os.path.exists(destPath): sourceTime = datetime.datetime.fromtimestamp(os.stat(source).st_mtime) destTime = datetime.datetime.fromtimestamp(os.stat(destPath).st_mtime) if sourceTime > destTime: shutil.copy2(source, destDir) else: shutil.copy2(source, destDir) def __createDirectories(self, dirName): if not os.path.exists(dirName): os.makedirs(dirName) def __createFiles(self, project, target): pkginfoPath = os.path.join(target, "Contents", "Pkginfo") if not os.path.exists(pkginfoPath) or self.__newerThanProject(pkginfoPath, project): f = file(pkginfoPath, "w") f.write(project.signature) f.close() def __newerThanProject(self, sourcePath, project): projectPath = os.path.join(devon.projectsFileName, project.path) projectTime = datetime.datetime.fromtimestamp(os.stat(projectPath).st_mtime) sourceTime = datetime.datetime.fromtimestamp(os.stat(sourcePath).st_mtime) return sourceTime > projectTime def getDirectorySize(path): size = 0 for root, dirs, files in os.walk(path): print "%s" % files size += sum([os.path.getsize(os.path.join(root, name)) for name in files]) # XXXjoe On OS X at least, the number is double its actual size for some reason return size/2
out << Block << text << Close
identifier_body
diskImage.py
import devon.maker from devon.tags import * import datetime, os.path, shutil # ************************************************************************************************** class DiskImage(devon.maker.MakerManyToOne): path = "hdiutil" def getTarget(self, project): return "%s.dmg" % project.name def needsUpdate(self, project, target): return True def build(self, project, out, sources, target): bytes = 0.0 for source in sources: bytes += getDirectorySize(source) # Pad the rounding error a little, or we'll run out of space when copying megabytes = bytes/1000000 + 0.2 out << Block("progressBox progress-build") << "Creating disk image " \ << FileLink(path=target) << target << Close << "..." \ << Close # Create the disk image line = "%s create '%s' -megabytes %f -volname '%s' -fs HFS+" \ % (self.path, target, megabytes, project.name) result = devon.make.executeCommand(project, self, line, out) # Mount the disk image line = "%s attach '%s'" % (self.path, target) result = devon.make.executeCommand(project, self, line, out) # Copy each file to the disk image volumeName = "/Volumes/%s/" % project.name for source in sources: os.system("cp -R '%s' '%s'" % (source, volumeName))
# Unmount the disk image line = "%s detach '%s'" % (self.path, volumeName) result = devon.make.executeCommand(project, self, line, out) return result def printAction(self, project, out, target): out << Block("progressBox progress-build") << "Archiving " \ << FileLink(path=target) << target << Close << "..." \ << Close def printResult(self, project, out, text): out << Block << text << Close def __copyFile(self, source, destDir): if os.path.isdir(source): newDest = os.path.join(destDir, os.path.basename(source)) if not os.path.exists(newDest): os.makedirs(newDest) paths = os.listdir(source) for fileName in [name for name in paths if not name[0] == "."]: fileSource = os.path.join(source, fileName) self.__copyFile(fileSource, newDest) else: destPath = os.path.join(destDir, os.path.basename(source)) if os.path.exists(destPath): sourceTime = datetime.datetime.fromtimestamp(os.stat(source).st_mtime) destTime = datetime.datetime.fromtimestamp(os.stat(destPath).st_mtime) if sourceTime > destTime: shutil.copy2(source, destDir) else: shutil.copy2(source, destDir) def __createDirectories(self, dirName): if not os.path.exists(dirName): os.makedirs(dirName) def __createFiles(self, project, target): pkginfoPath = os.path.join(target, "Contents", "Pkginfo") if not os.path.exists(pkginfoPath) or self.__newerThanProject(pkginfoPath, project): f = file(pkginfoPath, "w") f.write(project.signature) f.close() def __newerThanProject(self, sourcePath, project): projectPath = os.path.join(devon.projectsFileName, project.path) projectTime = datetime.datetime.fromtimestamp(os.stat(projectPath).st_mtime) sourceTime = datetime.datetime.fromtimestamp(os.stat(sourcePath).st_mtime) return sourceTime > projectTime def getDirectorySize(path): size = 0 for root, dirs, files in os.walk(path): print "%s" % files size += sum([os.path.getsize(os.path.join(root, name)) for name in files]) # XXXjoe On OS X at least, the number is double its actual size for some reason return size/2
random_line_split
diskImage.py
import devon.maker from devon.tags import * import datetime, os.path, shutil # ************************************************************************************************** class DiskImage(devon.maker.MakerManyToOne): path = "hdiutil" def getTarget(self, project): return "%s.dmg" % project.name def needsUpdate(self, project, target): return True def build(self, project, out, sources, target): bytes = 0.0 for source in sources: bytes += getDirectorySize(source) # Pad the rounding error a little, or we'll run out of space when copying megabytes = bytes/1000000 + 0.2 out << Block("progressBox progress-build") << "Creating disk image " \ << FileLink(path=target) << target << Close << "..." \ << Close # Create the disk image line = "%s create '%s' -megabytes %f -volname '%s' -fs HFS+" \ % (self.path, target, megabytes, project.name) result = devon.make.executeCommand(project, self, line, out) # Mount the disk image line = "%s attach '%s'" % (self.path, target) result = devon.make.executeCommand(project, self, line, out) # Copy each file to the disk image volumeName = "/Volumes/%s/" % project.name for source in sources: os.system("cp -R '%s' '%s'" % (source, volumeName)) # Unmount the disk image line = "%s detach '%s'" % (self.path, volumeName) result = devon.make.executeCommand(project, self, line, out) return result def printAction(self, project, out, target): out << Block("progressBox progress-build") << "Archiving " \ << FileLink(path=target) << target << Close << "..." \ << Close def printResult(self, project, out, text): out << Block << text << Close def __copyFile(self, source, destDir): if os.path.isdir(source): newDest = os.path.join(destDir, os.path.basename(source)) if not os.path.exists(newDest): os.makedirs(newDest) paths = os.listdir(source) for fileName in [name for name in paths if not name[0] == "."]: fileSource = os.path.join(source, fileName) self.__copyFile(fileSource, newDest) else: destPath = os.path.join(destDir, os.path.basename(source)) if os.path.exists(destPath): sourceTime = datetime.datetime.fromtimestamp(os.stat(source).st_mtime) destTime = datetime.datetime.fromtimestamp(os.stat(destPath).st_mtime) if sourceTime > destTime: shutil.copy2(source, destDir) else: shutil.copy2(source, destDir) def __createDirectories(self, dirName): if not os.path.exists(dirName): os.makedirs(dirName) def __createFiles(self, project, target): pkginfoPath = os.path.join(target, "Contents", "Pkginfo") if not os.path.exists(pkginfoPath) or self.__newerThanProject(pkginfoPath, project): f = file(pkginfoPath, "w") f.write(project.signature) f.close() def __newerThanProject(self, sourcePath, project): projectPath = os.path.join(devon.projectsFileName, project.path) projectTime = datetime.datetime.fromtimestamp(os.stat(projectPath).st_mtime) sourceTime = datetime.datetime.fromtimestamp(os.stat(sourcePath).st_mtime) return sourceTime > projectTime def getDirectorySize(path): size = 0 for root, dirs, files in os.walk(path):
# XXXjoe On OS X at least, the number is double its actual size for some reason return size/2
print "%s" % files size += sum([os.path.getsize(os.path.join(root, name)) for name in files])
conditional_block
diskImage.py
import devon.maker from devon.tags import * import datetime, os.path, shutil # ************************************************************************************************** class DiskImage(devon.maker.MakerManyToOne): path = "hdiutil" def getTarget(self, project): return "%s.dmg" % project.name def needsUpdate(self, project, target): return True def build(self, project, out, sources, target): bytes = 0.0 for source in sources: bytes += getDirectorySize(source) # Pad the rounding error a little, or we'll run out of space when copying megabytes = bytes/1000000 + 0.2 out << Block("progressBox progress-build") << "Creating disk image " \ << FileLink(path=target) << target << Close << "..." \ << Close # Create the disk image line = "%s create '%s' -megabytes %f -volname '%s' -fs HFS+" \ % (self.path, target, megabytes, project.name) result = devon.make.executeCommand(project, self, line, out) # Mount the disk image line = "%s attach '%s'" % (self.path, target) result = devon.make.executeCommand(project, self, line, out) # Copy each file to the disk image volumeName = "/Volumes/%s/" % project.name for source in sources: os.system("cp -R '%s' '%s'" % (source, volumeName)) # Unmount the disk image line = "%s detach '%s'" % (self.path, volumeName) result = devon.make.executeCommand(project, self, line, out) return result def
(self, project, out, target): out << Block("progressBox progress-build") << "Archiving " \ << FileLink(path=target) << target << Close << "..." \ << Close def printResult(self, project, out, text): out << Block << text << Close def __copyFile(self, source, destDir): if os.path.isdir(source): newDest = os.path.join(destDir, os.path.basename(source)) if not os.path.exists(newDest): os.makedirs(newDest) paths = os.listdir(source) for fileName in [name for name in paths if not name[0] == "."]: fileSource = os.path.join(source, fileName) self.__copyFile(fileSource, newDest) else: destPath = os.path.join(destDir, os.path.basename(source)) if os.path.exists(destPath): sourceTime = datetime.datetime.fromtimestamp(os.stat(source).st_mtime) destTime = datetime.datetime.fromtimestamp(os.stat(destPath).st_mtime) if sourceTime > destTime: shutil.copy2(source, destDir) else: shutil.copy2(source, destDir) def __createDirectories(self, dirName): if not os.path.exists(dirName): os.makedirs(dirName) def __createFiles(self, project, target): pkginfoPath = os.path.join(target, "Contents", "Pkginfo") if not os.path.exists(pkginfoPath) or self.__newerThanProject(pkginfoPath, project): f = file(pkginfoPath, "w") f.write(project.signature) f.close() def __newerThanProject(self, sourcePath, project): projectPath = os.path.join(devon.projectsFileName, project.path) projectTime = datetime.datetime.fromtimestamp(os.stat(projectPath).st_mtime) sourceTime = datetime.datetime.fromtimestamp(os.stat(sourcePath).st_mtime) return sourceTime > projectTime def getDirectorySize(path): size = 0 for root, dirs, files in os.walk(path): print "%s" % files size += sum([os.path.getsize(os.path.join(root, name)) for name in files]) # XXXjoe On OS X at least, the number is double its actual size for some reason return size/2
printAction
identifier_name
macro_parser.rs
// Copyright 2012-2014 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. // // ignore-lexer-test FIXME #15679 //! This is an Earley-like parser, without support for in-grammar nonterminals, //! only by calling out to the main rust parser for named nonterminals (which it //! commits to fully when it hits one in a grammar). This means that there are no //! completer or predictor rules, and therefore no need to store one column per //! token: instead, there's a set of current Earley items and a set of next //! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in //! pathological cases, is worse than traditional Earley parsing, but it's an //! easier fit for Macro-by-Example-style rules, and I think the overhead is //! lower. (In order to prevent the pathological case, we'd need to lazily //! construct the resulting `NamedMatch`es at the very end. It'd be a pain, //! and require more memory to keep around old items, but it would also save //! overhead) //! //! Quick intro to how the parser works: //! //! A 'position' is a dot in the middle of a matcher, usually represented as a //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`. //! //! The parser walks through the input a character at a time, maintaining a list //! of items consistent with the current position in the input string: `cur_eis`. //! //! As it processes them, it fills up `eof_eis` with items that would be valid if //! the macro invocation is now over, `bb_eis` with items that are waiting on //! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting //! on the a particular token. Most of the logic concerns moving the · through the //! repetitions indicated by Kleene stars. It only advances or calls out to the //! real Rust parser when no `cur_eis` items remain //! //! Example: Start parsing `a a a a b` against [· a $( a )* a b]. //! //! Remaining input: `a a a a b` //! next_eis: [· a $( a )* a b] //! //! - - - Advance over an `a`. - - - //! //! Remaining input: `a a a b` //! cur: [a · $( a )* a b] //! Descend/Skip (first item). //! next: [a $( · a )* a b] [a $( a )* · a b]. //! //! - - - Advance over an `a`. - - - //! //! Remaining input: `a a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] //! //! - - - Advance over a `b`. - - - //! //! Remaining input: `` //! eof: [a $( a )* a b ·] pub use self::NamedMatch::*; pub use self::ParseResult::*; use self::TokenTreeOrTokenTreeVec::*; use ast; use ast::{TokenTree, Ident}; use ast::{TtDelimited, TtSequence, TtToken}; use codemap::{BytePos, mk_sp, Span}; use codemap; use parse::lexer::*; //resolve bug? use parse::ParseSess; use parse::attr::ParserAttr; use parse::parser::{LifetimeAndTypesWithoutColons, Parser}; use parse::token::{Eof, DocComment, MatchNt, SubstNt}; use parse::token::{Token, Nonterminal}; use parse::token; use print::pprust; use ptr::P; use std::mem; use std::rc::Rc; use std::collections::HashMap; use std::collections::hash_map::Entry::{Vacant, Occupied}; // To avoid costly uniqueness checks, we require that `MatchSeq` always has // a nonempty body. #[derive(Clone)] enum TokenTreeOrTokenTreeVec { Tt(ast::TokenTree), TtSeq(Rc<Vec<ast::TokenTree>>), } impl TokenTreeOrTokenTreeVec { fn len(&self) -> usize { match self { &TtSeq(ref v) => v.len(), &Tt(ref tt) => tt.len(), } } fn get_tt(&self, index: usize) -> TokenTree { match self { &TtSeq(ref v) => v[index].clone(), &Tt(ref tt) => tt.get_tt(index), } } } /// an unzipping of `TokenTree`s #[derive(Clone)] struct MatcherTtFrame { elts: TokenTreeOrTokenTreeVec, idx: usize, } #[derive(Clone)] pub struct MatcherPos { stack: Vec<MatcherTtFrame>, top_elts: TokenTreeOrTokenTreeVec, sep: Option<Token>, idx: usize, up: Option<Box<MatcherPos>>, matches: Vec<Vec<Rc<NamedMatch>>>, match_lo: usize, match_cur: usize, match_hi: usize, sp_lo: BytePos, } pub fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { count + match elt { &TtSequence(_, ref seq) => { seq.num_captures
count_names(&delim.tts) } &TtToken(_, MatchNt(..)) => { 1 } &TtToken(_, _) => 0, } }) } pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos) -> Box<MatcherPos> { let match_idx_hi = count_names(&ms[..]); let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect(); box MatcherPos { stack: vec![], top_elts: TtSeq(ms), sep: sep, idx: 0, up: None, matches: matches, match_lo: 0, match_cur: 0, match_hi: match_idx_hi, sp_lo: lo } } /// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL: /// so it is associated with a single ident in a parse, and all /// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type /// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a /// single token::MATCH_NONTERMINAL in the TokenTree that produced it. /// /// The in-memory structure of a particular NamedMatch represents the match /// that occurred when a particular subset of a matcher was applied to a /// particular token tree. /// /// The width of each MatchedSeq in the NamedMatch, and the identity of the /// `MatchedNonterminal`s, will depend on the token tree it was applied to: /// each MatchedSeq corresponds to a single TTSeq in the originating /// token tree. The depth of the NamedMatch structure will therefore depend /// only on the nesting depth of `ast::TTSeq`s in the originating /// token tree it was derived from. pub enum NamedMatch { MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span), MatchedNonterminal(Nonterminal) } pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) -> HashMap<Ident, Rc<NamedMatch>> { fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>], ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) { match m { &TtSequence(_, ref seq) => { for next_m in &seq.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtDelimited(_, ref delim) => { for next_m in &delim.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtToken(sp, MatchNt(bind_name, _, _, _)) => { match ret_val.entry(bind_name) { Vacant(spot) => { spot.insert(res[*idx].clone()); *idx += 1; } Occupied(..) => { let string = token::get_ident(bind_name); p_s.span_diagnostic .span_fatal(sp, &format!("duplicated bind name: {}", &string)) } } } &TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"), &TtToken(_, _) => (), } } let mut ret_val = HashMap::new(); let mut idx = 0; for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) } ret_val } pub enum ParseResult<T> { Success(T), Failure(codemap::Span, String), Error(codemap::Span, String) } pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>; pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>; pub fn parse_or_else(sess: &ParseSess, cfg: ast::CrateConfig, rdr: TtReader, ms: Vec<TokenTree> ) -> HashMap<Ident, Rc<NamedMatch>> { match parse(sess, cfg, rdr, &ms[..]) { Success(m) => m, Failure(sp, str) => { sess.span_diagnostic.span_fatal(sp, &str[..]) } Error(sp, str) => { sess.span_diagnostic.span_fatal(sp, &str[..]) } } } /// Perform a token equality check, ignoring syntax context (that is, an /// unhygienic comparison) pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool { match (t1,t2) { (&token::Ident(id1,_),&token::Ident(id2,_)) | (&token::Lifetime(id1),&token::Lifetime(id2)) => id1.name == id2.name, _ => *t1 == *t2 } } pub fn parse(sess: &ParseSess, cfg: ast::CrateConfig, mut rdr: TtReader, ms: &[TokenTree]) -> NamedParseResult { let mut cur_eis = Vec::new(); cur_eis.push(initial_matcher_pos(Rc::new(ms.iter() .cloned() .collect()), None, rdr.peek().sp.lo)); loop { let mut bb_eis = Vec::new(); // black-box parsed by parser.rs let mut next_eis = Vec::new(); // or proceed normally let mut eof_eis = Vec::new(); let TokenAndSpan { tok, sp } = rdr.peek(); /* we append new items to this while we go */ loop { let mut ei = match cur_eis.pop() { None => break, /* for each Earley Item */ Some(ei) => ei, }; // When unzipped trees end, remove them while ei.idx >= ei.top_elts.len() { match ei.stack.pop() { Some(MatcherTtFrame { elts, idx }) => { ei.top_elts = elts; ei.idx = idx + 1; } None => break } } let idx = ei.idx; let len = ei.top_elts.len(); /* at end of sequence */ if idx >= len { // can't move out of `match`es, so: if ei.up.is_some() { // hack: a matcher sequence is repeating iff it has a // parent (the top level is just a container) // disregard separator, try to go up // (remove this condition to make trailing seps ok) if idx == len { // pop from the matcher position let mut new_pos = ei.up.clone().unwrap(); // update matches (the MBE "parse tree") by appending // each tree as a subtree. // I bet this is a perf problem: we're preemptively // doing a lot of array work that will get thrown away // most of the time. // Only touch the binders we have actually bound for idx in ei.match_lo..ei.match_hi { let sub = (ei.matches[idx]).clone(); (&mut new_pos.matches[idx]) .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo, sp.hi)))); } new_pos.match_cur = ei.match_hi; new_pos.idx += 1; cur_eis.push(new_pos); } // can we go around again? // the *_t vars are workarounds for the lack of unary move match ei.sep { Some(ref t) if idx == len => { // we need a separator // i'm conflicted about whether this should be hygienic.... // though in this case, if the separators are never legal // idents, it shouldn't matter. if token_name_eq(&tok, t) { //pass the separator let mut ei_t = ei.clone(); // ei_t.match_cur = ei_t.match_lo; ei_t.idx += 1; next_eis.push(ei_t); } } _ => { // we don't need a separator let mut ei_t = ei; ei_t.match_cur = ei_t.match_lo; ei_t.idx = 0; cur_eis.push(ei_t); } } } else { eof_eis.push(ei); } } else { match ei.top_elts.get_tt(idx) { /* need to descend into sequence */ TtSequence(sp, seq) => { if seq.op == ast::ZeroOrMore { let mut new_ei = ei.clone(); new_ei.match_cur += seq.num_captures; new_ei.idx += 1; //we specifically matched zero repeats. for idx in ei.match_cur..ei.match_cur + seq.num_captures { (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); } cur_eis.push(new_ei); } let matches: Vec<_> = (0..ei.matches.len()) .map(|_| Vec::new()).collect(); let ei_t = ei; cur_eis.push(box MatcherPos { stack: vec![], sep: seq.separator.clone(), idx: 0, matches: matches, match_lo: ei_t.match_cur, match_cur: ei_t.match_cur, match_hi: ei_t.match_cur + seq.num_captures, up: Some(ei_t), sp_lo: sp.lo, top_elts: Tt(TtSequence(sp, seq)), }); } TtToken(_, MatchNt(..)) => { // Built-in nonterminals never start with these tokens, // so we can eliminate them from consideration. match tok { token::CloseDelim(_) => {}, _ => bb_eis.push(ei), } } TtToken(sp, SubstNt(..)) => { return Error(sp, "Cannot transcribe in macro LHS".to_string()) } seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => { let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq)); let idx = ei.idx; ei.stack.push(MatcherTtFrame { elts: lower_elts, idx: idx, }); ei.idx = 0; cur_eis.push(ei); } TtToken(_, ref t) => { let mut ei_t = ei.clone(); if token_name_eq(t,&tok) { ei_t.idx += 1; next_eis.push(ei_t); } } } } } /* error messages here could be improved with links to orig. rules */ if token_name_eq(&tok, &token::Eof) { if eof_eis.len() == 1 { let mut v = Vec::new(); for dv in &mut (&mut eof_eis[0]).matches { v.push(dv.pop().unwrap()); } return Success(nameize(sess, ms, &v[..])); } else if eof_eis.len() > 1 { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { return Failure(sp, "unexpected end of macro invocation".to_string()); } } else { if (bb_eis.len() > 0 && next_eis.len() > 0) || bb_eis.len() > 1 { let nts = bb_eis.iter().map(|ei| { match ei.top_elts.get_tt(ei.idx) { TtToken(_, MatchNt(bind, name, _, _)) => { (format!("{} ('{}')", token::get_ident(name), token::get_ident(bind))).to_string() } _ => panic!() } }).collect::<Vec<String>>().connect(" or "); return Error(sp, format!( "local ambiguity: multiple parsing options: \ built-in NTs {} or {} other options.", nts, next_eis.len()).to_string()); } else if bb_eis.len() == 0 && next_eis.len() == 0 { return Failure(sp, format!("no rules expected the token `{}`", pprust::token_to_string(&tok)).to_string()); } else if next_eis.len() > 0 { /* Now process the next token */ while next_eis.len() > 0 { cur_eis.push(next_eis.pop().unwrap()); } rdr.next_token(); } else /* bb_eis.len() == 1 */ { let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone())); let mut ei = bb_eis.pop().unwrap(); match ei.top_elts.get_tt(ei.idx) { TtToken(span, MatchNt(_, name, _, _)) => { let name_string = token::get_ident(name); let match_cur = ei.match_cur; (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, span, &name_string)))); ei.idx += 1; ei.match_cur += 1; } _ => panic!() } cur_eis.push(ei); for _ in 0..rust_parser.tokens_consumed { let _ = rdr.next_token(); } } } assert!(cur_eis.len() > 0); } } pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal { match name { "tt" => { p.quote_depth += 1; //but in theory, non-quoted tts might be useful let res = token::NtTT(P(p.parse_token_tree())); p.quote_depth -= 1; return res; } _ => {} } // check at the beginning and the parser checks after each bump p.check_unknown_macro_variable(); match name { "item" => match p.parse_item() { Some(i) => token::NtItem(i), None => p.fatal("expected an item keyword") }, "block" => token::NtBlock(p.parse_block()), "stmt" => match p.parse_stmt() { Some(s) => token::NtStmt(s), None => p.fatal("expected a statement") }, "pat" => token::NtPat(p.parse_pat()), "expr" => token::NtExpr(p.parse_expr()), "ty" => token::NtTy(p.parse_ty()), // this could be handled like a token, since it is one "ident" => match p.token { token::Ident(sn,b) => { p.bump(); token::NtIdent(box sn,b) } _ => { let token_str = pprust::token_to_string(&p.token); p.fatal(&format!("expected ident, found {}", &token_str[..])) } }, "path" => { token::NtPath(box p.parse_path(LifetimeAndTypesWithoutColons)) } "meta" => token::NtMeta(p.parse_meta_item()), _ => { p.span_fatal_help(sp, &format!("invalid fragment specifier `{}`", name), "valid fragment specifiers are `ident`, `block`, \ `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \ and `item`") } } }
} &TtDelimited(_, ref delim) => {
random_line_split
macro_parser.rs
// Copyright 2012-2014 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. // // ignore-lexer-test FIXME #15679 //! This is an Earley-like parser, without support for in-grammar nonterminals, //! only by calling out to the main rust parser for named nonterminals (which it //! commits to fully when it hits one in a grammar). This means that there are no //! completer or predictor rules, and therefore no need to store one column per //! token: instead, there's a set of current Earley items and a set of next //! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in //! pathological cases, is worse than traditional Earley parsing, but it's an //! easier fit for Macro-by-Example-style rules, and I think the overhead is //! lower. (In order to prevent the pathological case, we'd need to lazily //! construct the resulting `NamedMatch`es at the very end. It'd be a pain, //! and require more memory to keep around old items, but it would also save //! overhead) //! //! Quick intro to how the parser works: //! //! A 'position' is a dot in the middle of a matcher, usually represented as a //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`. //! //! The parser walks through the input a character at a time, maintaining a list //! of items consistent with the current position in the input string: `cur_eis`. //! //! As it processes them, it fills up `eof_eis` with items that would be valid if //! the macro invocation is now over, `bb_eis` with items that are waiting on //! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting //! on the a particular token. Most of the logic concerns moving the · through the //! repetitions indicated by Kleene stars. It only advances or calls out to the //! real Rust parser when no `cur_eis` items remain //! //! Example: Start parsing `a a a a b` against [· a $( a )* a b]. //! //! Remaining input: `a a a a b` //! next_eis: [· a $( a )* a b] //! //! - - - Advance over an `a`. - - - //! //! Remaining input: `a a a b` //! cur: [a · $( a )* a b] //! Descend/Skip (first item). //! next: [a $( · a )* a b] [a $( a )* · a b]. //! //! - - - Advance over an `a`. - - - //! //! Remaining input: `a a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] //! //! - - - Advance over a `b`. - - - //! //! Remaining input: `` //! eof: [a $( a )* a b ·] pub use self::NamedMatch::*; pub use self::ParseResult::*; use self::TokenTreeOrTokenTreeVec::*; use ast; use ast::{TokenTree, Ident}; use ast::{TtDelimited, TtSequence, TtToken}; use codemap::{BytePos, mk_sp, Span}; use codemap; use parse::lexer::*; //resolve bug? use parse::ParseSess; use parse::attr::ParserAttr; use parse::parser::{LifetimeAndTypesWithoutColons, Parser}; use parse::token::{Eof, DocComment, MatchNt, SubstNt}; use parse::token::{Token, Nonterminal}; use parse::token; use print::pprust; use ptr::P; use std::mem; use std::rc::Rc; use std::collections::HashMap; use std::collections::hash_map::Entry::{Vacant, Occupied}; // To avoid costly uniqueness checks, we require that `MatchSeq` always has // a nonempty body. #[derive(Clone)] enum TokenTreeOrTokenTreeVec { Tt(ast::TokenTree), TtSeq(Rc<Vec<ast::TokenTree>>), } impl TokenTreeOrTokenTreeVec { fn len(&self) -> usize { match self { &TtSeq(ref v) => v.len(), &Tt(ref tt) => tt.len(), } } fn get_tt(&self, index: us
> TokenTree { match self { &TtSeq(ref v) => v[index].clone(), &Tt(ref tt) => tt.get_tt(index), } } } /// an unzipping of `TokenTree`s #[derive(Clone)] struct MatcherTtFrame { elts: TokenTreeOrTokenTreeVec, idx: usize, } #[derive(Clone)] pub struct MatcherPos { stack: Vec<MatcherTtFrame>, top_elts: TokenTreeOrTokenTreeVec, sep: Option<Token>, idx: usize, up: Option<Box<MatcherPos>>, matches: Vec<Vec<Rc<NamedMatch>>>, match_lo: usize, match_cur: usize, match_hi: usize, sp_lo: BytePos, } pub fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { count + match elt { &TtSequence(_, ref seq) => { seq.num_captures } &TtDelimited(_, ref delim) => { count_names(&delim.tts) } &TtToken(_, MatchNt(..)) => { 1 } &TtToken(_, _) => 0, } }) } pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos) -> Box<MatcherPos> { let match_idx_hi = count_names(&ms[..]); let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect(); box MatcherPos { stack: vec![], top_elts: TtSeq(ms), sep: sep, idx: 0, up: None, matches: matches, match_lo: 0, match_cur: 0, match_hi: match_idx_hi, sp_lo: lo } } /// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL: /// so it is associated with a single ident in a parse, and all /// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type /// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a /// single token::MATCH_NONTERMINAL in the TokenTree that produced it. /// /// The in-memory structure of a particular NamedMatch represents the match /// that occurred when a particular subset of a matcher was applied to a /// particular token tree. /// /// The width of each MatchedSeq in the NamedMatch, and the identity of the /// `MatchedNonterminal`s, will depend on the token tree it was applied to: /// each MatchedSeq corresponds to a single TTSeq in the originating /// token tree. The depth of the NamedMatch structure will therefore depend /// only on the nesting depth of `ast::TTSeq`s in the originating /// token tree it was derived from. pub enum NamedMatch { MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span), MatchedNonterminal(Nonterminal) } pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) -> HashMap<Ident, Rc<NamedMatch>> { fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>], ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) { match m { &TtSequence(_, ref seq) => { for next_m in &seq.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtDelimited(_, ref delim) => { for next_m in &delim.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtToken(sp, MatchNt(bind_name, _, _, _)) => { match ret_val.entry(bind_name) { Vacant(spot) => { spot.insert(res[*idx].clone()); *idx += 1; } Occupied(..) => { let string = token::get_ident(bind_name); p_s.span_diagnostic .span_fatal(sp, &format!("duplicated bind name: {}", &string)) } } } &TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"), &TtToken(_, _) => (), } } let mut ret_val = HashMap::new(); let mut idx = 0; for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) } ret_val } pub enum ParseResult<T> { Success(T), Failure(codemap::Span, String), Error(codemap::Span, String) } pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>; pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>; pub fn parse_or_else(sess: &ParseSess, cfg: ast::CrateConfig, rdr: TtReader, ms: Vec<TokenTree> ) -> HashMap<Ident, Rc<NamedMatch>> { match parse(sess, cfg, rdr, &ms[..]) { Success(m) => m, Failure(sp, str) => { sess.span_diagnostic.span_fatal(sp, &str[..]) } Error(sp, str) => { sess.span_diagnostic.span_fatal(sp, &str[..]) } } } /// Perform a token equality check, ignoring syntax context (that is, an /// unhygienic comparison) pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool { match (t1,t2) { (&token::Ident(id1,_),&token::Ident(id2,_)) | (&token::Lifetime(id1),&token::Lifetime(id2)) => id1.name == id2.name, _ => *t1 == *t2 } } pub fn parse(sess: &ParseSess, cfg: ast::CrateConfig, mut rdr: TtReader, ms: &[TokenTree]) -> NamedParseResult { let mut cur_eis = Vec::new(); cur_eis.push(initial_matcher_pos(Rc::new(ms.iter() .cloned() .collect()), None, rdr.peek().sp.lo)); loop { let mut bb_eis = Vec::new(); // black-box parsed by parser.rs let mut next_eis = Vec::new(); // or proceed normally let mut eof_eis = Vec::new(); let TokenAndSpan { tok, sp } = rdr.peek(); /* we append new items to this while we go */ loop { let mut ei = match cur_eis.pop() { None => break, /* for each Earley Item */ Some(ei) => ei, }; // When unzipped trees end, remove them while ei.idx >= ei.top_elts.len() { match ei.stack.pop() { Some(MatcherTtFrame { elts, idx }) => { ei.top_elts = elts; ei.idx = idx + 1; } None => break } } let idx = ei.idx; let len = ei.top_elts.len(); /* at end of sequence */ if idx >= len { // can't move out of `match`es, so: if ei.up.is_some() { // hack: a matcher sequence is repeating iff it has a // parent (the top level is just a container) // disregard separator, try to go up // (remove this condition to make trailing seps ok) if idx == len { // pop from the matcher position let mut new_pos = ei.up.clone().unwrap(); // update matches (the MBE "parse tree") by appending // each tree as a subtree. // I bet this is a perf problem: we're preemptively // doing a lot of array work that will get thrown away // most of the time. // Only touch the binders we have actually bound for idx in ei.match_lo..ei.match_hi { let sub = (ei.matches[idx]).clone(); (&mut new_pos.matches[idx]) .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo, sp.hi)))); } new_pos.match_cur = ei.match_hi; new_pos.idx += 1; cur_eis.push(new_pos); } // can we go around again? // the *_t vars are workarounds for the lack of unary move match ei.sep { Some(ref t) if idx == len => { // we need a separator // i'm conflicted about whether this should be hygienic.... // though in this case, if the separators are never legal // idents, it shouldn't matter. if token_name_eq(&tok, t) { //pass the separator let mut ei_t = ei.clone(); // ei_t.match_cur = ei_t.match_lo; ei_t.idx += 1; next_eis.push(ei_t); } } _ => { // we don't need a separator let mut ei_t = ei; ei_t.match_cur = ei_t.match_lo; ei_t.idx = 0; cur_eis.push(ei_t); } } } else { eof_eis.push(ei); } } else { match ei.top_elts.get_tt(idx) { /* need to descend into sequence */ TtSequence(sp, seq) => { if seq.op == ast::ZeroOrMore { let mut new_ei = ei.clone(); new_ei.match_cur += seq.num_captures; new_ei.idx += 1; //we specifically matched zero repeats. for idx in ei.match_cur..ei.match_cur + seq.num_captures { (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); } cur_eis.push(new_ei); } let matches: Vec<_> = (0..ei.matches.len()) .map(|_| Vec::new()).collect(); let ei_t = ei; cur_eis.push(box MatcherPos { stack: vec![], sep: seq.separator.clone(), idx: 0, matches: matches, match_lo: ei_t.match_cur, match_cur: ei_t.match_cur, match_hi: ei_t.match_cur + seq.num_captures, up: Some(ei_t), sp_lo: sp.lo, top_elts: Tt(TtSequence(sp, seq)), }); } TtToken(_, MatchNt(..)) => { // Built-in nonterminals never start with these tokens, // so we can eliminate them from consideration. match tok { token::CloseDelim(_) => {}, _ => bb_eis.push(ei), } } TtToken(sp, SubstNt(..)) => { return Error(sp, "Cannot transcribe in macro LHS".to_string()) } seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => { let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq)); let idx = ei.idx; ei.stack.push(MatcherTtFrame { elts: lower_elts, idx: idx, }); ei.idx = 0; cur_eis.push(ei); } TtToken(_, ref t) => { let mut ei_t = ei.clone(); if token_name_eq(t,&tok) { ei_t.idx += 1; next_eis.push(ei_t); } } } } } /* error messages here could be improved with links to orig. rules */ if token_name_eq(&tok, &token::Eof) { if eof_eis.len() == 1 { let mut v = Vec::new(); for dv in &mut (&mut eof_eis[0]).matches { v.push(dv.pop().unwrap()); } return Success(nameize(sess, ms, &v[..])); } else if eof_eis.len() > 1 { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { return Failure(sp, "unexpected end of macro invocation".to_string()); } } else { if (bb_eis.len() > 0 && next_eis.len() > 0) || bb_eis.len() > 1 { let nts = bb_eis.iter().map(|ei| { match ei.top_elts.get_tt(ei.idx) { TtToken(_, MatchNt(bind, name, _, _)) => { (format!("{} ('{}')", token::get_ident(name), token::get_ident(bind))).to_string() } _ => panic!() } }).collect::<Vec<String>>().connect(" or "); return Error(sp, format!( "local ambiguity: multiple parsing options: \ built-in NTs {} or {} other options.", nts, next_eis.len()).to_string()); } else if bb_eis.len() == 0 && next_eis.len() == 0 { return Failure(sp, format!("no rules expected the token `{}`", pprust::token_to_string(&tok)).to_string()); } else if next_eis.len() > 0 { /* Now process the next token */ while next_eis.len() > 0 { cur_eis.push(next_eis.pop().unwrap()); } rdr.next_token(); } else /* bb_eis.len() == 1 */ { let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone())); let mut ei = bb_eis.pop().unwrap(); match ei.top_elts.get_tt(ei.idx) { TtToken(span, MatchNt(_, name, _, _)) => { let name_string = token::get_ident(name); let match_cur = ei.match_cur; (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, span, &name_string)))); ei.idx += 1; ei.match_cur += 1; } _ => panic!() } cur_eis.push(ei); for _ in 0..rust_parser.tokens_consumed { let _ = rdr.next_token(); } } } assert!(cur_eis.len() > 0); } } pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal { match name { "tt" => { p.quote_depth += 1; //but in theory, non-quoted tts might be useful let res = token::NtTT(P(p.parse_token_tree())); p.quote_depth -= 1; return res; } _ => {} } // check at the beginning and the parser checks after each bump p.check_unknown_macro_variable(); match name { "item" => match p.parse_item() { Some(i) => token::NtItem(i), None => p.fatal("expected an item keyword") }, "block" => token::NtBlock(p.parse_block()), "stmt" => match p.parse_stmt() { Some(s) => token::NtStmt(s), None => p.fatal("expected a statement") }, "pat" => token::NtPat(p.parse_pat()), "expr" => token::NtExpr(p.parse_expr()), "ty" => token::NtTy(p.parse_ty()), // this could be handled like a token, since it is one "ident" => match p.token { token::Ident(sn,b) => { p.bump(); token::NtIdent(box sn,b) } _ => { let token_str = pprust::token_to_string(&p.token); p.fatal(&format!("expected ident, found {}", &token_str[..])) } }, "path" => { token::NtPath(box p.parse_path(LifetimeAndTypesWithoutColons)) } "meta" => token::NtMeta(p.parse_meta_item()), _ => { p.span_fatal_help(sp, &format!("invalid fragment specifier `{}`", name), "valid fragment specifiers are `ident`, `block`, \ `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \ and `item`") } } }
ize) -
identifier_name
macro_parser.rs
// Copyright 2012-2014 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. // // ignore-lexer-test FIXME #15679 //! This is an Earley-like parser, without support for in-grammar nonterminals, //! only by calling out to the main rust parser for named nonterminals (which it //! commits to fully when it hits one in a grammar). This means that there are no //! completer or predictor rules, and therefore no need to store one column per //! token: instead, there's a set of current Earley items and a set of next //! ones. Instead of NTs, we have a special case for Kleene star. The big-O, in //! pathological cases, is worse than traditional Earley parsing, but it's an //! easier fit for Macro-by-Example-style rules, and I think the overhead is //! lower. (In order to prevent the pathological case, we'd need to lazily //! construct the resulting `NamedMatch`es at the very end. It'd be a pain, //! and require more memory to keep around old items, but it would also save //! overhead) //! //! Quick intro to how the parser works: //! //! A 'position' is a dot in the middle of a matcher, usually represented as a //! dot. For example `· a $( a )* a b` is a position, as is `a $( · a )* a b`. //! //! The parser walks through the input a character at a time, maintaining a list //! of items consistent with the current position in the input string: `cur_eis`. //! //! As it processes them, it fills up `eof_eis` with items that would be valid if //! the macro invocation is now over, `bb_eis` with items that are waiting on //! a Rust nonterminal like `$e:expr`, and `next_eis` with items that are waiting //! on the a particular token. Most of the logic concerns moving the · through the //! repetitions indicated by Kleene stars. It only advances or calls out to the //! real Rust parser when no `cur_eis` items remain //! //! Example: Start parsing `a a a a b` against [· a $( a )* a b]. //! //! Remaining input: `a a a a b` //! next_eis: [· a $( a )* a b] //! //! - - - Advance over an `a`. - - - //! //! Remaining input: `a a a b` //! cur: [a · $( a )* a b] //! Descend/Skip (first item). //! next: [a $( · a )* a b] [a $( a )* · a b]. //! //! - - - Advance over an `a`. - - - //! //! Remaining input: `a a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `a b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] [a $( a )* a · b] //! //! - - - Advance over an `a`. - - - (this looks exactly like the last step) //! //! Remaining input: `b` //! cur: [a $( a · )* a b] next: [a $( a )* a · b] //! Finish/Repeat (first item) //! next: [a $( a )* · a b] [a $( · a )* a b] //! //! - - - Advance over a `b`. - - - //! //! Remaining input: `` //! eof: [a $( a )* a b ·] pub use self::NamedMatch::*; pub use self::ParseResult::*; use self::TokenTreeOrTokenTreeVec::*; use ast; use ast::{TokenTree, Ident}; use ast::{TtDelimited, TtSequence, TtToken}; use codemap::{BytePos, mk_sp, Span}; use codemap; use parse::lexer::*; //resolve bug? use parse::ParseSess; use parse::attr::ParserAttr; use parse::parser::{LifetimeAndTypesWithoutColons, Parser}; use parse::token::{Eof, DocComment, MatchNt, SubstNt}; use parse::token::{Token, Nonterminal}; use parse::token; use print::pprust; use ptr::P; use std::mem; use std::rc::Rc; use std::collections::HashMap; use std::collections::hash_map::Entry::{Vacant, Occupied}; // To avoid costly uniqueness checks, we require that `MatchSeq` always has // a nonempty body. #[derive(Clone)] enum TokenTreeOrTokenTreeVec { Tt(ast::TokenTree), TtSeq(Rc<Vec<ast::TokenTree>>), } impl TokenTreeOrTokenTreeVec { fn len(&self) -> usize { match self { &TtSeq(ref v) => v.len(), &Tt(ref tt) => tt.len(), } } fn get_tt(&self, index: usize) -> TokenTree { match self { &TtSeq(ref v) => v[index].clone(), &Tt(ref tt) => tt.get_tt(index), } } } /// an unzipping of `TokenTree`s #[derive(Clone)] struct MatcherTtFrame { elts: TokenTreeOrTokenTreeVec, idx: usize, } #[derive(Clone)] pub struct MatcherPos { stack: Vec<MatcherTtFrame>, top_elts: TokenTreeOrTokenTreeVec, sep: Option<Token>, idx: usize, up: Option<Box<MatcherPos>>, matches: Vec<Vec<Rc<NamedMatch>>>, match_lo: usize, match_cur: usize, match_hi: usize, sp_lo: BytePos, } pub fn count_names(ms: &[TokenTree]) -> usize { ms.iter().fold(0, |count, elt| { count + match elt { &TtSequence(_, ref seq) => { seq.num_captures } &TtDelimited(_, ref delim) => { count_names(&delim.tts) } &TtToken(_, MatchNt(..)) => { 1 } &TtToken(_, _) => 0, } }) } pub fn initial_matcher_pos(ms: Rc<Vec<TokenTree>>, sep: Option<Token>, lo: BytePos) -> Box<MatcherPos> { let match_idx_hi = count_names(&ms[..]); let matches: Vec<_> = (0..match_idx_hi).map(|_| Vec::new()).collect(); box MatcherPos { stack: vec![], top_elts: TtSeq(ms), sep: sep, idx: 0, up: None, matches: matches, match_lo: 0, match_cur: 0, match_hi: match_idx_hi, sp_lo: lo } } /// NamedMatch is a pattern-match result for a single token::MATCH_NONTERMINAL: /// so it is associated with a single ident in a parse, and all /// `MatchedNonterminal`s in the NamedMatch have the same nonterminal type /// (expr, item, etc). Each leaf in a single NamedMatch corresponds to a /// single token::MATCH_NONTERMINAL in the TokenTree that produced it. /// /// The in-memory structure of a particular NamedMatch represents the match /// that occurred when a particular subset of a matcher was applied to a /// particular token tree. /// /// The width of each MatchedSeq in the NamedMatch, and the identity of the /// `MatchedNonterminal`s, will depend on the token tree it was applied to: /// each MatchedSeq corresponds to a single TTSeq in the originating /// token tree. The depth of the NamedMatch structure will therefore depend /// only on the nesting depth of `ast::TTSeq`s in the originating /// token tree it was derived from. pub enum NamedMatch { MatchedSeq(Vec<Rc<NamedMatch>>, codemap::Span), MatchedNonterminal(Nonterminal) } pub fn nameize(p_s: &ParseSess, ms: &[TokenTree], res: &[Rc<NamedMatch>]) -> HashMap<Ident, Rc<NamedMatch>> { fn n_rec(p_s: &ParseSess, m: &TokenTree, res: &[Rc<NamedMatch>], ret_val: &mut HashMap<Ident, Rc<NamedMatch>>, idx: &mut usize) { match m { &TtSequence(_, ref seq) => { for next_m in &seq.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtDelimited(_, ref delim) => { for next_m in &delim.tts { n_rec(p_s, next_m, res, ret_val, idx) } } &TtToken(sp, MatchNt(bind_name, _, _, _)) => { match ret_val.entry(bind_name) { Vacant(spot) => { spot.insert(res[*idx].clone()); *idx += 1; } Occupied(..) => { let string = token::get_ident(bind_name); p_s.span_diagnostic .span_fatal(sp, &format!("duplicated bind name: {}", &string)) } } } &TtToken(_, SubstNt(..)) => panic!("Cannot fill in a NT"), &TtToken(_, _) => (), } } let mut ret_val = HashMap::new(); let mut idx = 0; for m in ms { n_rec(p_s, m, res, &mut ret_val, &mut idx) } ret_val } pub enum ParseResult<T> { Success(T), Failure(codemap::Span, String), Error(codemap::Span, String) } pub type NamedParseResult = ParseResult<HashMap<Ident, Rc<NamedMatch>>>; pub type PositionalParseResult = ParseResult<Vec<Rc<NamedMatch>>>; pub fn parse_or_else(sess: &ParseSess, cfg: ast::CrateConfig, rdr: TtReader, ms: Vec<TokenTree> ) -> HashMap<Ident, Rc<NamedMatch>> { match parse(sess, cfg, rdr, &ms[..]) { Success(m) => m, Failure(sp, str) => { sess.span_diagnostic.span_fatal(sp, &str[..]) } Error(sp, str) => { sess.span_diagnostic.span_fatal(sp, &str[..]) } } } /// Perform a token equality check, ignoring syntax context (that is, an /// unhygienic comparison) pub fn token_name_eq(t1 : &Token, t2 : &Token) -> bool { match (t1,t2) { (&token::Ident(id1,_),&token::Ident(id2,_)) | (&token::Lifetime(id1),&token::Lifetime(id2)) => id1.name == id2.name, _ => *t1 == *t2 } } pub fn parse(sess: &ParseSess, cfg: ast::CrateConfig, mut rdr: TtReader, ms: &[TokenTree]) -> NamedParseResult { let mut cur_eis = Vec::new(); cur_eis.push(initial_matcher_pos(Rc::new(ms.iter() .cloned() .collect()), None, rdr.peek().sp.lo)); loop { let mut bb_eis = Vec::new(); // black-box parsed by parser.rs let mut next_eis = Vec::new(); // or proceed normally let mut eof_eis = Vec::new(); let TokenAndSpan { tok, sp } = rdr.peek(); /* we append new items to this while we go */ loop { let mut ei = match cur_eis.pop() { None => break, /* for each Earley Item */ Some(ei) => ei, }; // When unzipped trees end, remove them while ei.idx >= ei.top_elts.len() { match ei.stack.pop() { Some(MatcherTtFrame { elts, idx }) => { ei.top_elts = elts; ei.idx = idx + 1; } None => break } } let idx = ei.idx; let len = ei.top_elts.len(); /* at end of sequence */ if idx >= len { // can't move out of `match`es, so: if ei.up.is_some() { // hack: a matcher sequence is repeating iff it has a // parent (the top level is just a container) // disregard separator, try to go up // (remove this condition to make trailing seps ok) if idx == len { // pop from the matcher position let mut new_pos = ei.up.clone().unwrap(); // update matches (the MBE "parse tree") by appending // each tree as a subtree. // I bet this is a perf problem: we're preemptively // doing a lot of array work that will get thrown away // most of the time. // Only touch the binders we have actually bound for idx in ei.match_lo..ei.match_hi { let sub = (ei.matches[idx]).clone(); (&mut new_pos.matches[idx]) .push(Rc::new(MatchedSeq(sub, mk_sp(ei.sp_lo, sp.hi)))); } new_pos.match_cur = ei.match_hi; new_pos.idx += 1; cur_eis.push(new_pos); } // can we go around again? // the *_t vars are workarounds for the lack of unary move match ei.sep { Some(ref t) if idx == len => { // we need a separator // i'm conflicted about whether this should be hygienic.... // though in this case, if the separators are never legal // idents, it shouldn't matter. if token_name_eq(&tok, t) { //pass the separator let mut ei_t = ei.clone(); // ei_t.match_cur = ei_t.match_lo; ei_t.idx += 1; next_eis.push(ei_t); } } _ => { // we don't need a separator let mut ei_t = ei; ei_t.match_cur = ei_t.match_lo; ei_t.idx = 0; cur_eis.push(ei_t); } } } else { eof_eis.push(ei); } } else { match ei.top_elts.get_tt(idx) { /* need to descend into sequence */ TtSequence(sp, seq) => { if seq.op == ast::ZeroOrMore { let mut new_ei = ei.clone(); new_ei.match_cur += seq.num_captures; new_ei.idx += 1; //we specifically matched zero repeats. for idx in ei.match_cur..ei.match_cur + seq.num_captures { (&mut new_ei.matches[idx]).push(Rc::new(MatchedSeq(vec![], sp))); } cur_eis.push(new_ei); } let matches: Vec<_> = (0..ei.matches.len()) .map(|_| Vec::new()).collect(); let ei_t = ei; cur_eis.push(box MatcherPos { stack: vec![], sep: seq.separator.clone(), idx: 0, matches: matches, match_lo: ei_t.match_cur, match_cur: ei_t.match_cur, match_hi: ei_t.match_cur + seq.num_captures, up: Some(ei_t), sp_lo: sp.lo, top_elts: Tt(TtSequence(sp, seq)), }); } TtToken(_, MatchNt(..)) => {
Token(sp, SubstNt(..)) => { return Error(sp, "Cannot transcribe in macro LHS".to_string()) } seq @ TtDelimited(..) | seq @ TtToken(_, DocComment(..)) => { let lower_elts = mem::replace(&mut ei.top_elts, Tt(seq)); let idx = ei.idx; ei.stack.push(MatcherTtFrame { elts: lower_elts, idx: idx, }); ei.idx = 0; cur_eis.push(ei); } TtToken(_, ref t) => { let mut ei_t = ei.clone(); if token_name_eq(t,&tok) { ei_t.idx += 1; next_eis.push(ei_t); } } } } } /* error messages here could be improved with links to orig. rules */ if token_name_eq(&tok, &token::Eof) { if eof_eis.len() == 1 { let mut v = Vec::new(); for dv in &mut (&mut eof_eis[0]).matches { v.push(dv.pop().unwrap()); } return Success(nameize(sess, ms, &v[..])); } else if eof_eis.len() > 1 { return Error(sp, "ambiguity: multiple successful parses".to_string()); } else { return Failure(sp, "unexpected end of macro invocation".to_string()); } } else { if (bb_eis.len() > 0 && next_eis.len() > 0) || bb_eis.len() > 1 { let nts = bb_eis.iter().map(|ei| { match ei.top_elts.get_tt(ei.idx) { TtToken(_, MatchNt(bind, name, _, _)) => { (format!("{} ('{}')", token::get_ident(name), token::get_ident(bind))).to_string() } _ => panic!() } }).collect::<Vec<String>>().connect(" or "); return Error(sp, format!( "local ambiguity: multiple parsing options: \ built-in NTs {} or {} other options.", nts, next_eis.len()).to_string()); } else if bb_eis.len() == 0 && next_eis.len() == 0 { return Failure(sp, format!("no rules expected the token `{}`", pprust::token_to_string(&tok)).to_string()); } else if next_eis.len() > 0 { /* Now process the next token */ while next_eis.len() > 0 { cur_eis.push(next_eis.pop().unwrap()); } rdr.next_token(); } else /* bb_eis.len() == 1 */ { let mut rust_parser = Parser::new(sess, cfg.clone(), Box::new(rdr.clone())); let mut ei = bb_eis.pop().unwrap(); match ei.top_elts.get_tt(ei.idx) { TtToken(span, MatchNt(_, name, _, _)) => { let name_string = token::get_ident(name); let match_cur = ei.match_cur; (&mut ei.matches[match_cur]).push(Rc::new(MatchedNonterminal( parse_nt(&mut rust_parser, span, &name_string)))); ei.idx += 1; ei.match_cur += 1; } _ => panic!() } cur_eis.push(ei); for _ in 0..rust_parser.tokens_consumed { let _ = rdr.next_token(); } } } assert!(cur_eis.len() > 0); } } pub fn parse_nt(p: &mut Parser, sp: Span, name: &str) -> Nonterminal { match name { "tt" => { p.quote_depth += 1; //but in theory, non-quoted tts might be useful let res = token::NtTT(P(p.parse_token_tree())); p.quote_depth -= 1; return res; } _ => {} } // check at the beginning and the parser checks after each bump p.check_unknown_macro_variable(); match name { "item" => match p.parse_item() { Some(i) => token::NtItem(i), None => p.fatal("expected an item keyword") }, "block" => token::NtBlock(p.parse_block()), "stmt" => match p.parse_stmt() { Some(s) => token::NtStmt(s), None => p.fatal("expected a statement") }, "pat" => token::NtPat(p.parse_pat()), "expr" => token::NtExpr(p.parse_expr()), "ty" => token::NtTy(p.parse_ty()), // this could be handled like a token, since it is one "ident" => match p.token { token::Ident(sn,b) => { p.bump(); token::NtIdent(box sn,b) } _ => { let token_str = pprust::token_to_string(&p.token); p.fatal(&format!("expected ident, found {}", &token_str[..])) } }, "path" => { token::NtPath(box p.parse_path(LifetimeAndTypesWithoutColons)) } "meta" => token::NtMeta(p.parse_meta_item()), _ => { p.span_fatal_help(sp, &format!("invalid fragment specifier `{}`", name), "valid fragment specifiers are `ident`, `block`, \ `stmt`, `expr`, `pat`, `ty`, `path`, `meta`, `tt` \ and `item`") } } }
// Built-in nonterminals never start with these tokens, // so we can eliminate them from consideration. match tok { token::CloseDelim(_) => {}, _ => bb_eis.push(ei), } } Tt
conditional_block
_metrics_advisor.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING from azure.core import AsyncPipelineClient from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import MetricsAdvisorConfiguration from .operations import MetricsAdvisorOperationsMixin from .. import models class
(MetricsAdvisorOperationsMixin): """Microsoft Azure Metrics Advisor REST API (OpenAPI v2). :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:`<resource-name>`.cognitiveservices.azure.com). :type endpoint: str """ def __init__( self, credential: "AsyncTokenCredential", endpoint: str, **kwargs: Any ) -> None: base_url = '{endpoint}/metricsadvisor/v1.0' self._config = MetricsAdvisorConfiguration(credential, endpoint, **kwargs) self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "MetricsAdvisor": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
MetricsAdvisor
identifier_name
_metrics_advisor.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING from azure.core import AsyncPipelineClient from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import MetricsAdvisorConfiguration from .operations import MetricsAdvisorOperationsMixin from .. import models class MetricsAdvisor(MetricsAdvisorOperationsMixin): """Microsoft Azure Metrics Advisor REST API (OpenAPI v2). :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:`<resource-name>`.cognitiveservices.azure.com). :type endpoint: str """ def __init__( self, credential: "AsyncTokenCredential", endpoint: str, **kwargs: Any ) -> None: base_url = '{endpoint}/metricsadvisor/v1.0' self._config = MetricsAdvisorConfiguration(credential, endpoint, **kwargs) self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None:
async def __aenter__(self) -> "MetricsAdvisor": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
await self._client.close()
identifier_body
_metrics_advisor.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING from azure.core import AsyncPipelineClient from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports from azure.core.credentials_async import AsyncTokenCredential from ._configuration import MetricsAdvisorConfiguration from .operations import MetricsAdvisorOperationsMixin from .. import models class MetricsAdvisor(MetricsAdvisorOperationsMixin): """Microsoft Azure Metrics Advisor REST API (OpenAPI v2). :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:`<resource-name>`.cognitiveservices.azure.com).
""" def __init__( self, credential: "AsyncTokenCredential", endpoint: str, **kwargs: Any ) -> None: base_url = '{endpoint}/metricsadvisor/v1.0' self._config = MetricsAdvisorConfiguration(credential, endpoint, **kwargs) self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "MetricsAdvisor": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
:type endpoint: str
random_line_split
_metrics_advisor.py
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, TYPE_CHECKING from azure.core import AsyncPipelineClient from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from msrest import Deserializer, Serializer if TYPE_CHECKING: # pylint: disable=unused-import,ungrouped-imports
from ._configuration import MetricsAdvisorConfiguration from .operations import MetricsAdvisorOperationsMixin from .. import models class MetricsAdvisor(MetricsAdvisorOperationsMixin): """Microsoft Azure Metrics Advisor REST API (OpenAPI v2). :param credential: Credential needed for the client to connect to Azure. :type credential: ~azure.core.credentials_async.AsyncTokenCredential :param endpoint: Supported Cognitive Services endpoints (protocol and hostname, for example: https://:code:`<resource-name>`.cognitiveservices.azure.com). :type endpoint: str """ def __init__( self, credential: "AsyncTokenCredential", endpoint: str, **kwargs: Any ) -> None: base_url = '{endpoint}/metricsadvisor/v1.0' self._config = MetricsAdvisorConfiguration(credential, endpoint, **kwargs) self._client = AsyncPipelineClient(base_url=base_url, config=self._config, **kwargs) client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} self._serialize = Serializer(client_models) self._serialize.client_side_validation = False self._deserialize = Deserializer(client_models) async def _send_request(self, http_request: HttpRequest, **kwargs: Any) -> AsyncHttpResponse: """Runs the network request through the client's chained policies. :param http_request: The network request you want to make. Required. :type http_request: ~azure.core.pipeline.transport.HttpRequest :keyword bool stream: Whether the response payload will be streamed. Defaults to True. :return: The response of your network call. Does not do error handling on your response. :rtype: ~azure.core.pipeline.transport.AsyncHttpResponse """ path_format_arguments = { 'endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } http_request.url = self._client.format_url(http_request.url, **path_format_arguments) stream = kwargs.pop("stream", True) pipeline_response = await self._client._pipeline.run(http_request, stream=stream, **kwargs) return pipeline_response.http_response async def close(self) -> None: await self._client.close() async def __aenter__(self) -> "MetricsAdvisor": await self._client.__aenter__() return self async def __aexit__(self, *exc_details) -> None: await self._client.__aexit__(*exc_details)
from azure.core.credentials_async import AsyncTokenCredential
conditional_block
macro_crate_test.rs
// Copyright 2013-2015 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. // force-host #![feature(plugin_registrar, quote, rustc_private)] extern crate syntax; extern crate rustc; use syntax::ast::{self, TokenTree, Item, MetaItem, ImplItem, TraitItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::{self, token}; use syntax::ptr::P; use rustc::plugin::Registry; #[macro_export] macro_rules! exported_macro { () => (2) } macro_rules! unexported_macro { () => (3) } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_macro("identity", expand_identity); reg.register_syntax_extension( token::intern("into_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. Modifier(Box::new(expand_into_foo))); reg.register_syntax_extension( token::intern("into_multi_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiModifier(Box::new(expand_into_foo_multi))); reg.register_syntax_extension( token::intern("duplicate"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiDecorator(Box::new(expand_duplicate))); } fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { if !tts.is_empty() { cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacEager::expr(quote_expr!(cx, 1)) } // See Issue #15750 fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { // Parse an expression and emit it unchanged. let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec()); let expr = parser.parse_expr(); MacEager::expr(quote_expr!(&mut *cx, $expr)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: P<Item>) -> P<Item> { P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() }) } fn expand_into_foo_multi(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: Annotatable) -> Annotatable { match it { Annotatable::Item(it) => { Annotatable::Item(P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo2 { Bar2, Baz2 }).unwrap()).clone() })) } Annotatable::ImplItem(it) => { quote_item!(cx, impl X { fn foo(&self) -> i32 { 42 } }).unwrap().and_then(|i| { match i.node { ast::ItemImpl(_, _, _, _, _, mut items) => { Annotatable::ImplItem(items.pop().expect("impl method not found")) } _ => unreachable!("impl parsed to something other than impl") } }) } Annotatable::TraitItem(it) => { quote_item!(cx, trait X { fn foo(&self) -> i32 { 0 } }).unwrap().and_then(|i| { match i.node { ast::ItemTrait(_, _, _, mut items) => { Annotatable::TraitItem(items.pop().expect("trait method not found")) } _ => unreachable!("trait parsed to something other than trait") } }) } } } // Create a duplicate of the annotatable, based on the MetaItem fn expand_duplicate(cx: &mut ExtCtxt, sp: Span, mi: &MetaItem, it: &Annotatable, push: &mut FnMut(Annotatable)) { let copy_name = match mi.node { ast::MetaItem_::MetaList(_, ref xs) => { if let ast::MetaItem_::MetaWord(ref w) = xs[0].node { token::str_to_ident(&w) } else { cx.span_err(mi.span, "Expected word"); return; } } _ => { cx.span_err(mi.span, "Expected list"); return; } }; // Duplicate the item but replace its ident by the MetaItem match it.clone() { Annotatable::Item(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::Item(P(new_it))); } Annotatable::ImplItem(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::ImplItem(P(new_it))); } Annotatable::TraitItem(tt) =>
} } pub fn foo() {}
{ let mut new_it = (*tt).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::TraitItem(P(new_it))); }
conditional_block
macro_crate_test.rs
// Copyright 2013-2015 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. // force-host #![feature(plugin_registrar, quote, rustc_private)] extern crate syntax; extern crate rustc; use syntax::ast::{self, TokenTree, Item, MetaItem, ImplItem, TraitItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::{self, token}; use syntax::ptr::P; use rustc::plugin::Registry; #[macro_export] macro_rules! exported_macro { () => (2) } macro_rules! unexported_macro { () => (3) } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_macro("identity", expand_identity); reg.register_syntax_extension( token::intern("into_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. Modifier(Box::new(expand_into_foo))); reg.register_syntax_extension( token::intern("into_multi_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiModifier(Box::new(expand_into_foo_multi))); reg.register_syntax_extension( token::intern("duplicate"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiDecorator(Box::new(expand_duplicate))); } fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { if !tts.is_empty() { cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacEager::expr(quote_expr!(cx, 1)) } // See Issue #15750 fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { // Parse an expression and emit it unchanged. let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec()); let expr = parser.parse_expr(); MacEager::expr(quote_expr!(&mut *cx, $expr)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: P<Item>) -> P<Item> { P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() }) } fn
(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: Annotatable) -> Annotatable { match it { Annotatable::Item(it) => { Annotatable::Item(P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo2 { Bar2, Baz2 }).unwrap()).clone() })) } Annotatable::ImplItem(it) => { quote_item!(cx, impl X { fn foo(&self) -> i32 { 42 } }).unwrap().and_then(|i| { match i.node { ast::ItemImpl(_, _, _, _, _, mut items) => { Annotatable::ImplItem(items.pop().expect("impl method not found")) } _ => unreachable!("impl parsed to something other than impl") } }) } Annotatable::TraitItem(it) => { quote_item!(cx, trait X { fn foo(&self) -> i32 { 0 } }).unwrap().and_then(|i| { match i.node { ast::ItemTrait(_, _, _, mut items) => { Annotatable::TraitItem(items.pop().expect("trait method not found")) } _ => unreachable!("trait parsed to something other than trait") } }) } } } // Create a duplicate of the annotatable, based on the MetaItem fn expand_duplicate(cx: &mut ExtCtxt, sp: Span, mi: &MetaItem, it: &Annotatable, push: &mut FnMut(Annotatable)) { let copy_name = match mi.node { ast::MetaItem_::MetaList(_, ref xs) => { if let ast::MetaItem_::MetaWord(ref w) = xs[0].node { token::str_to_ident(&w) } else { cx.span_err(mi.span, "Expected word"); return; } } _ => { cx.span_err(mi.span, "Expected list"); return; } }; // Duplicate the item but replace its ident by the MetaItem match it.clone() { Annotatable::Item(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::Item(P(new_it))); } Annotatable::ImplItem(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::ImplItem(P(new_it))); } Annotatable::TraitItem(tt) => { let mut new_it = (*tt).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::TraitItem(P(new_it))); } } } pub fn foo() {}
expand_into_foo_multi
identifier_name
macro_crate_test.rs
// Copyright 2013-2015 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. // force-host #![feature(plugin_registrar, quote, rustc_private)] extern crate syntax; extern crate rustc; use syntax::ast::{self, TokenTree, Item, MetaItem, ImplItem, TraitItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::{self, token}; use syntax::ptr::P; use rustc::plugin::Registry; #[macro_export] macro_rules! exported_macro { () => (2) } macro_rules! unexported_macro { () => (3) } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_macro("identity", expand_identity); reg.register_syntax_extension( token::intern("into_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. Modifier(Box::new(expand_into_foo))); reg.register_syntax_extension( token::intern("into_multi_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiModifier(Box::new(expand_into_foo_multi))); reg.register_syntax_extension( token::intern("duplicate"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiDecorator(Box::new(expand_duplicate))); }
cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacEager::expr(quote_expr!(cx, 1)) } // See Issue #15750 fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { // Parse an expression and emit it unchanged. let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec()); let expr = parser.parse_expr(); MacEager::expr(quote_expr!(&mut *cx, $expr)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: P<Item>) -> P<Item> { P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() }) } fn expand_into_foo_multi(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: Annotatable) -> Annotatable { match it { Annotatable::Item(it) => { Annotatable::Item(P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo2 { Bar2, Baz2 }).unwrap()).clone() })) } Annotatable::ImplItem(it) => { quote_item!(cx, impl X { fn foo(&self) -> i32 { 42 } }).unwrap().and_then(|i| { match i.node { ast::ItemImpl(_, _, _, _, _, mut items) => { Annotatable::ImplItem(items.pop().expect("impl method not found")) } _ => unreachable!("impl parsed to something other than impl") } }) } Annotatable::TraitItem(it) => { quote_item!(cx, trait X { fn foo(&self) -> i32 { 0 } }).unwrap().and_then(|i| { match i.node { ast::ItemTrait(_, _, _, mut items) => { Annotatable::TraitItem(items.pop().expect("trait method not found")) } _ => unreachable!("trait parsed to something other than trait") } }) } } } // Create a duplicate of the annotatable, based on the MetaItem fn expand_duplicate(cx: &mut ExtCtxt, sp: Span, mi: &MetaItem, it: &Annotatable, push: &mut FnMut(Annotatable)) { let copy_name = match mi.node { ast::MetaItem_::MetaList(_, ref xs) => { if let ast::MetaItem_::MetaWord(ref w) = xs[0].node { token::str_to_ident(&w) } else { cx.span_err(mi.span, "Expected word"); return; } } _ => { cx.span_err(mi.span, "Expected list"); return; } }; // Duplicate the item but replace its ident by the MetaItem match it.clone() { Annotatable::Item(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::Item(P(new_it))); } Annotatable::ImplItem(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::ImplItem(P(new_it))); } Annotatable::TraitItem(tt) => { let mut new_it = (*tt).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::TraitItem(P(new_it))); } } } pub fn foo() {}
fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { if !tts.is_empty() {
random_line_split
macro_crate_test.rs
// Copyright 2013-2015 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. // force-host #![feature(plugin_registrar, quote, rustc_private)] extern crate syntax; extern crate rustc; use syntax::ast::{self, TokenTree, Item, MetaItem, ImplItem, TraitItem}; use syntax::codemap::Span; use syntax::ext::base::*; use syntax::parse::{self, token}; use syntax::ptr::P; use rustc::plugin::Registry; #[macro_export] macro_rules! exported_macro { () => (2) } macro_rules! unexported_macro { () => (3) } #[plugin_registrar] pub fn plugin_registrar(reg: &mut Registry) { reg.register_macro("make_a_1", expand_make_a_1); reg.register_macro("identity", expand_identity); reg.register_syntax_extension( token::intern("into_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. Modifier(Box::new(expand_into_foo))); reg.register_syntax_extension( token::intern("into_multi_foo"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiModifier(Box::new(expand_into_foo_multi))); reg.register_syntax_extension( token::intern("duplicate"), // FIXME (#22405): Replace `Box::new` with `box` here when/if possible. MultiDecorator(Box::new(expand_duplicate))); } fn expand_make_a_1(cx: &mut ExtCtxt, sp: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { if !tts.is_empty() { cx.span_fatal(sp, "make_a_1 takes no arguments"); } MacEager::expr(quote_expr!(cx, 1)) } // See Issue #15750 fn expand_identity(cx: &mut ExtCtxt, _span: Span, tts: &[TokenTree]) -> Box<MacResult+'static> { // Parse an expression and emit it unchanged. let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(), tts.to_vec()); let expr = parser.parse_expr(); MacEager::expr(quote_expr!(&mut *cx, $expr)) } fn expand_into_foo(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: P<Item>) -> P<Item>
fn expand_into_foo_multi(cx: &mut ExtCtxt, sp: Span, attr: &MetaItem, it: Annotatable) -> Annotatable { match it { Annotatable::Item(it) => { Annotatable::Item(P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo2 { Bar2, Baz2 }).unwrap()).clone() })) } Annotatable::ImplItem(it) => { quote_item!(cx, impl X { fn foo(&self) -> i32 { 42 } }).unwrap().and_then(|i| { match i.node { ast::ItemImpl(_, _, _, _, _, mut items) => { Annotatable::ImplItem(items.pop().expect("impl method not found")) } _ => unreachable!("impl parsed to something other than impl") } }) } Annotatable::TraitItem(it) => { quote_item!(cx, trait X { fn foo(&self) -> i32 { 0 } }).unwrap().and_then(|i| { match i.node { ast::ItemTrait(_, _, _, mut items) => { Annotatable::TraitItem(items.pop().expect("trait method not found")) } _ => unreachable!("trait parsed to something other than trait") } }) } } } // Create a duplicate of the annotatable, based on the MetaItem fn expand_duplicate(cx: &mut ExtCtxt, sp: Span, mi: &MetaItem, it: &Annotatable, push: &mut FnMut(Annotatable)) { let copy_name = match mi.node { ast::MetaItem_::MetaList(_, ref xs) => { if let ast::MetaItem_::MetaWord(ref w) = xs[0].node { token::str_to_ident(&w) } else { cx.span_err(mi.span, "Expected word"); return; } } _ => { cx.span_err(mi.span, "Expected list"); return; } }; // Duplicate the item but replace its ident by the MetaItem match it.clone() { Annotatable::Item(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::Item(P(new_it))); } Annotatable::ImplItem(it) => { let mut new_it = (*it).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::ImplItem(P(new_it))); } Annotatable::TraitItem(tt) => { let mut new_it = (*tt).clone(); new_it.attrs.clear(); new_it.ident = copy_name; push(Annotatable::TraitItem(P(new_it))); } } } pub fn foo() {}
{ P(Item { attrs: it.attrs.clone(), ..(*quote_item!(cx, enum Foo { Bar, Baz }).unwrap()).clone() }) }
identifier_body
token.js
import RepositoryService from 'consul-ui/services/repository'; import { get } from '@ember/object'; import { Promise } from 'rsvp'; import { PRIMARY_KEY, SLUG_KEY } from 'consul-ui/models/token'; import statusFactory from 'consul-ui/utils/acls-status'; import isValidServerErrorFactory from 'consul-ui/utils/http/acl/is-valid-server-error'; const isValidServerError = isValidServerErrorFactory(); const status = statusFactory(isValidServerError, Promise); const MODEL_NAME = 'token'; export default RepositoryService.extend({ getModelName: function() { return MODEL_NAME; }, getPrimaryKey: function() { return PRIMARY_KEY; }, getSlugKey: function() { return SLUG_KEY; }, status: function(obj) { return status(obj); }, self: function(secret, dc) { return this.store .self(this.getModelName(), { secret: secret, dc: dc, }) .catch(e => { // If we get this 500 RPC error, it means we are a legacy ACL cluster // set AccessorID to null - which for the frontend means legacy mode if (isValidServerError(e))
return Promise.reject(e); }); }, clone: function(item) { return this.store.clone(this.getModelName(), get(item, PRIMARY_KEY)); }, findByPolicy: function(id, dc, nspace) { return this.store.query(this.getModelName(), { policy: id, dc: dc, ns: nspace, }); }, findByRole: function(id, dc, nspace) { return this.store.query(this.getModelName(), { role: id, dc: dc, ns: nspace, }); }, });
{ return { AccessorID: null, SecretID: secret, }; }
conditional_block
token.js
import RepositoryService from 'consul-ui/services/repository'; import { get } from '@ember/object'; import { Promise } from 'rsvp'; import { PRIMARY_KEY, SLUG_KEY } from 'consul-ui/models/token'; import statusFactory from 'consul-ui/utils/acls-status'; import isValidServerErrorFactory from 'consul-ui/utils/http/acl/is-valid-server-error'; const isValidServerError = isValidServerErrorFactory(); const status = statusFactory(isValidServerError, Promise); const MODEL_NAME = 'token'; export default RepositoryService.extend({ getModelName: function() { return MODEL_NAME;
return PRIMARY_KEY; }, getSlugKey: function() { return SLUG_KEY; }, status: function(obj) { return status(obj); }, self: function(secret, dc) { return this.store .self(this.getModelName(), { secret: secret, dc: dc, }) .catch(e => { // If we get this 500 RPC error, it means we are a legacy ACL cluster // set AccessorID to null - which for the frontend means legacy mode if (isValidServerError(e)) { return { AccessorID: null, SecretID: secret, }; } return Promise.reject(e); }); }, clone: function(item) { return this.store.clone(this.getModelName(), get(item, PRIMARY_KEY)); }, findByPolicy: function(id, dc, nspace) { return this.store.query(this.getModelName(), { policy: id, dc: dc, ns: nspace, }); }, findByRole: function(id, dc, nspace) { return this.store.query(this.getModelName(), { role: id, dc: dc, ns: nspace, }); }, });
}, getPrimaryKey: function() {
random_line_split
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::NoSuchChannel(ref chan) =>
} } } impl error::Error for BusError { fn description(&self) -> &str { match *self { BusError::NoSuchChannel(_) => "No such channel", } } } pub struct BusSystem { busses: HashMap<String, bus::Bus<f64>>, } impl BusSystem { // ok, there's a big fat leak : when there are no listenner to a bus, it stays in the map. pub fn new() -> BusSystem { BusSystem { busses: HashMap::new() } } // ideally sub<T> -> Receiver<T> pub fn sub(&mut self, chan: &str) -> Reader<f64> { self.busses .entry(chan.to_string()) .or_insert(bus::Bus::new(0.0)) .subscribe() } pub fn publish(&mut self, chan: &str, value: f64) -> Result<(), BusError> { self.busses.get_mut(chan).map(|c| c.publish(value)).ok_or( BusError::NoSuchChannel(chan.to_string()), ) } } #[cfg(test)] mod tests { use super::*; struct Stuff { a: Reader<f64>, b: Reader<f64>, } impl Stuff { fn doit(&self) -> f64 { self.a.value() + self.b.value() } } #[test] fn test_bus_system() { let mut bus = BusSystem::new(); let stuff = Stuff { a: bus.sub("a"), b: bus.sub("b"), }; bus.publish("a", 2.0).unwrap(); bus.publish("b", 4.0).unwrap(); assert_eq!(stuff.doit(), 6.0); assert!(bus.publish("b", 5.0).is_ok()); assert!(bus.publish("d", 5.0).is_err()); } }
{ fmt.debug_struct("NoSuchChannel") .field("channel", &chan) .finish() }
conditional_block
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::NoSuchChannel(ref chan) => { fmt.debug_struct("NoSuchChannel") .field("channel", &chan) .finish() } } } } impl error::Error for BusError { fn description(&self) -> &str { match *self { BusError::NoSuchChannel(_) => "No such channel", } } } pub struct BusSystem { busses: HashMap<String, bus::Bus<f64>>, } impl BusSystem { // ok, there's a big fat leak : when there are no listenner to a bus, it stays in the map. pub fn new() -> BusSystem { BusSystem { busses: HashMap::new() } } // ideally sub<T> -> Receiver<T> pub fn sub(&mut self, chan: &str) -> Reader<f64> { self.busses .entry(chan.to_string()) .or_insert(bus::Bus::new(0.0)) .subscribe() } pub fn publish(&mut self, chan: &str, value: f64) -> Result<(), BusError> { self.busses.get_mut(chan).map(|c| c.publish(value)).ok_or( BusError::NoSuchChannel(chan.to_string()), ) } } #[cfg(test)] mod tests { use super::*; struct
{ a: Reader<f64>, b: Reader<f64>, } impl Stuff { fn doit(&self) -> f64 { self.a.value() + self.b.value() } } #[test] fn test_bus_system() { let mut bus = BusSystem::new(); let stuff = Stuff { a: bus.sub("a"), b: bus.sub("b"), }; bus.publish("a", 2.0).unwrap(); bus.publish("b", 4.0).unwrap(); assert_eq!(stuff.doit(), 6.0); assert!(bus.publish("b", 5.0).is_ok()); assert!(bus.publish("d", 5.0).is_err()); } }
Stuff
identifier_name
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::NoSuchChannel(ref chan) => { fmt.debug_struct("NoSuchChannel") .field("channel", &chan) .finish() } } } } impl error::Error for BusError { fn description(&self) -> &str { match *self { BusError::NoSuchChannel(_) => "No such channel", } } } pub struct BusSystem { busses: HashMap<String, bus::Bus<f64>>, } impl BusSystem { // ok, there's a big fat leak : when there are no listenner to a bus, it stays in the map. pub fn new() -> BusSystem { BusSystem { busses: HashMap::new() } } // ideally sub<T> -> Receiver<T> pub fn sub(&mut self, chan: &str) -> Reader<f64>
pub fn publish(&mut self, chan: &str, value: f64) -> Result<(), BusError> { self.busses.get_mut(chan).map(|c| c.publish(value)).ok_or( BusError::NoSuchChannel(chan.to_string()), ) } } #[cfg(test)] mod tests { use super::*; struct Stuff { a: Reader<f64>, b: Reader<f64>, } impl Stuff { fn doit(&self) -> f64 { self.a.value() + self.b.value() } } #[test] fn test_bus_system() { let mut bus = BusSystem::new(); let stuff = Stuff { a: bus.sub("a"), b: bus.sub("b"), }; bus.publish("a", 2.0).unwrap(); bus.publish("b", 4.0).unwrap(); assert_eq!(stuff.doit(), 6.0); assert!(bus.publish("b", 5.0).is_ok()); assert!(bus.publish("d", 5.0).is_err()); } }
{ self.busses .entry(chan.to_string()) .or_insert(bus::Bus::new(0.0)) .subscribe() }
identifier_body
mod.rs
mod sender; mod bus; use std::error; use std::fmt; use std::collections::HashMap; pub use self::sender::Reader; #[derive(Debug)] pub enum BusError { NoSuchChannel(String), } impl fmt::Display for BusError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { match *self { BusError::NoSuchChannel(ref chan) => { fmt.debug_struct("NoSuchChannel") .field("channel", &chan) .finish() } } } } impl error::Error for BusError { fn description(&self) -> &str { match *self { BusError::NoSuchChannel(_) => "No such channel", } }
pub struct BusSystem { busses: HashMap<String, bus::Bus<f64>>, } impl BusSystem { // ok, there's a big fat leak : when there are no listenner to a bus, it stays in the map. pub fn new() -> BusSystem { BusSystem { busses: HashMap::new() } } // ideally sub<T> -> Receiver<T> pub fn sub(&mut self, chan: &str) -> Reader<f64> { self.busses .entry(chan.to_string()) .or_insert(bus::Bus::new(0.0)) .subscribe() } pub fn publish(&mut self, chan: &str, value: f64) -> Result<(), BusError> { self.busses.get_mut(chan).map(|c| c.publish(value)).ok_or( BusError::NoSuchChannel(chan.to_string()), ) } } #[cfg(test)] mod tests { use super::*; struct Stuff { a: Reader<f64>, b: Reader<f64>, } impl Stuff { fn doit(&self) -> f64 { self.a.value() + self.b.value() } } #[test] fn test_bus_system() { let mut bus = BusSystem::new(); let stuff = Stuff { a: bus.sub("a"), b: bus.sub("b"), }; bus.publish("a", 2.0).unwrap(); bus.publish("b", 4.0).unwrap(); assert_eq!(stuff.doit(), 6.0); assert!(bus.publish("b", 5.0).is_ok()); assert!(bus.publish("d", 5.0).is_err()); } }
}
random_line_split
pluggable_scm.ts
/* * Copyright 2022 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Stream from "mithril/stream"; import {Errors, ErrorsJSON} from "models/mixins/errors"; import {ValidatableMixin} from "models/mixins/new_validatable_mixin"; import {Origin, OriginJSON, OriginType} from "models/origin"; import {Configurations, PropertyJSON} from "models/shared/configuration"; export interface ScmsJSON { _embedded: EmbeddedJSON; } interface EmbeddedJSON { scms: ScmJSON[]; } export interface ScmJSON { id: string; name: string; auto_update: boolean; origin?: OriginJSON; plugin_metadata: PluginMetadataJSON; configuration: PropertyJSON[]; errors?: ErrorsJSON; } export interface PluginMetadataJSON { id: string; version: string; } export interface ScmUsageJSON { group: string; pipeline: string; } export interface ScmUsagesJSON { usages: ScmUsageJSON[]; } export class PluginMetadata extends ValidatableMixin { id: Stream<string>; version: Stream<string>; constructor(id: string, version: string) { super(); this.id = Stream(id); this.version = Stream(version); this.validatePresenceOf("id"); } static fromJSON(data: PluginMetadataJSON): PluginMetadata { return new PluginMetadata(data.id, data.version); } } export class Scm extends ValidatableMixin { id: Stream<string>; name: Stream<string>; autoUpdate: Stream<boolean>; origin = Stream<Origin>(); pluginMetadata: Stream<PluginMetadata>; configuration: Stream<Configurations>; constructor(id: string, name: string, autoUpdate: boolean, origin: Origin, pluginMetadata: PluginMetadata, configuration: Configurations) { super(); this.id = Stream(id); this.name = Stream(name); this.autoUpdate = Stream(autoUpdate); this.origin = Stream(origin); this.pluginMetadata = Stream(pluginMetadata); this.configuration = Stream(configuration); this.validatePresenceOf("name"); this.validateFormatOf("name", new RegExp("^[-a-zA-Z0-9_][-a-zA-Z0-9_.]*$"), {message: "Invalid Name. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period)."}); this.validateMaxLength("name", 255, {message: "The maximum allowed length is 255 characters."}); this.validateAssociated("pluginMetadata"); } static fromJSON(data: ScmJSON): Scm { const origin = data.origin ? Origin.fromJSON(data.origin) : new Origin(OriginType.GoCD); const scm = new Scm(data.id, data.name, data.auto_update, origin, PluginMetadata.fromJSON(data.plugin_metadata), Configurations.fromJSON(data.configuration)); scm.errors(new Errors(data.errors)); return scm; } toJSON(): object { return { id: this.id(), name: this.name(), auto_update: this.autoUpdate(), plugin_metadata: { id: this.pluginMetadata().id(), version: this.pluginMetadata().version() }, configuration: this.configuration().toJSON() }; } } export class Scms extends Array<Scm> { constructor(...vals: Scm[])
static fromJSON(data: ScmJSON[]): Scms { return new Scms(...data.map((a) => Scm.fromJSON(a))); } } class ScmUsage { group: string; pipeline: string; constructor(group: string, pipeline: string) { this.group = group; this.pipeline = pipeline; } static fromJSON(data: ScmUsageJSON): ScmUsage { return new ScmUsage(data.group, data.pipeline); } } export class ScmUsages extends Array<ScmUsage> { constructor(...vals: ScmUsage[]) { super(...vals); Object.setPrototypeOf(this, Object.create(ScmUsages.prototype)); } static fromJSON(data: ScmUsagesJSON): ScmUsages { return new ScmUsages(...data.usages.map((a) => ScmUsage.fromJSON(a))); } }
{ super(...vals); Object.setPrototypeOf(this, Object.create(Scms.prototype)); }
identifier_body
pluggable_scm.ts
/* * Copyright 2022 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Stream from "mithril/stream"; import {Errors, ErrorsJSON} from "models/mixins/errors"; import {ValidatableMixin} from "models/mixins/new_validatable_mixin"; import {Origin, OriginJSON, OriginType} from "models/origin"; import {Configurations, PropertyJSON} from "models/shared/configuration"; export interface ScmsJSON { _embedded: EmbeddedJSON; } interface EmbeddedJSON { scms: ScmJSON[]; } export interface ScmJSON { id: string; name: string; auto_update: boolean; origin?: OriginJSON; plugin_metadata: PluginMetadataJSON; configuration: PropertyJSON[]; errors?: ErrorsJSON; } export interface PluginMetadataJSON { id: string; version: string; } export interface ScmUsageJSON { group: string; pipeline: string; } export interface ScmUsagesJSON { usages: ScmUsageJSON[]; } export class PluginMetadata extends ValidatableMixin { id: Stream<string>; version: Stream<string>; constructor(id: string, version: string) { super();
this.version = Stream(version); this.validatePresenceOf("id"); } static fromJSON(data: PluginMetadataJSON): PluginMetadata { return new PluginMetadata(data.id, data.version); } } export class Scm extends ValidatableMixin { id: Stream<string>; name: Stream<string>; autoUpdate: Stream<boolean>; origin = Stream<Origin>(); pluginMetadata: Stream<PluginMetadata>; configuration: Stream<Configurations>; constructor(id: string, name: string, autoUpdate: boolean, origin: Origin, pluginMetadata: PluginMetadata, configuration: Configurations) { super(); this.id = Stream(id); this.name = Stream(name); this.autoUpdate = Stream(autoUpdate); this.origin = Stream(origin); this.pluginMetadata = Stream(pluginMetadata); this.configuration = Stream(configuration); this.validatePresenceOf("name"); this.validateFormatOf("name", new RegExp("^[-a-zA-Z0-9_][-a-zA-Z0-9_.]*$"), {message: "Invalid Name. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period)."}); this.validateMaxLength("name", 255, {message: "The maximum allowed length is 255 characters."}); this.validateAssociated("pluginMetadata"); } static fromJSON(data: ScmJSON): Scm { const origin = data.origin ? Origin.fromJSON(data.origin) : new Origin(OriginType.GoCD); const scm = new Scm(data.id, data.name, data.auto_update, origin, PluginMetadata.fromJSON(data.plugin_metadata), Configurations.fromJSON(data.configuration)); scm.errors(new Errors(data.errors)); return scm; } toJSON(): object { return { id: this.id(), name: this.name(), auto_update: this.autoUpdate(), plugin_metadata: { id: this.pluginMetadata().id(), version: this.pluginMetadata().version() }, configuration: this.configuration().toJSON() }; } } export class Scms extends Array<Scm> { constructor(...vals: Scm[]) { super(...vals); Object.setPrototypeOf(this, Object.create(Scms.prototype)); } static fromJSON(data: ScmJSON[]): Scms { return new Scms(...data.map((a) => Scm.fromJSON(a))); } } class ScmUsage { group: string; pipeline: string; constructor(group: string, pipeline: string) { this.group = group; this.pipeline = pipeline; } static fromJSON(data: ScmUsageJSON): ScmUsage { return new ScmUsage(data.group, data.pipeline); } } export class ScmUsages extends Array<ScmUsage> { constructor(...vals: ScmUsage[]) { super(...vals); Object.setPrototypeOf(this, Object.create(ScmUsages.prototype)); } static fromJSON(data: ScmUsagesJSON): ScmUsages { return new ScmUsages(...data.usages.map((a) => ScmUsage.fromJSON(a))); } }
this.id = Stream(id);
random_line_split
pluggable_scm.ts
/* * Copyright 2022 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import Stream from "mithril/stream"; import {Errors, ErrorsJSON} from "models/mixins/errors"; import {ValidatableMixin} from "models/mixins/new_validatable_mixin"; import {Origin, OriginJSON, OriginType} from "models/origin"; import {Configurations, PropertyJSON} from "models/shared/configuration"; export interface ScmsJSON { _embedded: EmbeddedJSON; } interface EmbeddedJSON { scms: ScmJSON[]; } export interface ScmJSON { id: string; name: string; auto_update: boolean; origin?: OriginJSON; plugin_metadata: PluginMetadataJSON; configuration: PropertyJSON[]; errors?: ErrorsJSON; } export interface PluginMetadataJSON { id: string; version: string; } export interface ScmUsageJSON { group: string; pipeline: string; } export interface ScmUsagesJSON { usages: ScmUsageJSON[]; } export class PluginMetadata extends ValidatableMixin { id: Stream<string>; version: Stream<string>; constructor(id: string, version: string) { super(); this.id = Stream(id); this.version = Stream(version); this.validatePresenceOf("id"); } static fromJSON(data: PluginMetadataJSON): PluginMetadata { return new PluginMetadata(data.id, data.version); } } export class Scm extends ValidatableMixin { id: Stream<string>; name: Stream<string>; autoUpdate: Stream<boolean>; origin = Stream<Origin>(); pluginMetadata: Stream<PluginMetadata>; configuration: Stream<Configurations>; constructor(id: string, name: string, autoUpdate: boolean, origin: Origin, pluginMetadata: PluginMetadata, configuration: Configurations) { super(); this.id = Stream(id); this.name = Stream(name); this.autoUpdate = Stream(autoUpdate); this.origin = Stream(origin); this.pluginMetadata = Stream(pluginMetadata); this.configuration = Stream(configuration); this.validatePresenceOf("name"); this.validateFormatOf("name", new RegExp("^[-a-zA-Z0-9_][-a-zA-Z0-9_.]*$"), {message: "Invalid Name. This must be alphanumeric and can contain underscores, hyphens and periods (however, it cannot start with a period)."}); this.validateMaxLength("name", 255, {message: "The maximum allowed length is 255 characters."}); this.validateAssociated("pluginMetadata"); } static fromJSON(data: ScmJSON): Scm { const origin = data.origin ? Origin.fromJSON(data.origin) : new Origin(OriginType.GoCD); const scm = new Scm(data.id, data.name, data.auto_update, origin, PluginMetadata.fromJSON(data.plugin_metadata), Configurations.fromJSON(data.configuration)); scm.errors(new Errors(data.errors)); return scm; } toJSON(): object { return { id: this.id(), name: this.name(), auto_update: this.autoUpdate(), plugin_metadata: { id: this.pluginMetadata().id(), version: this.pluginMetadata().version() }, configuration: this.configuration().toJSON() }; } } export class Scms extends Array<Scm> { constructor(...vals: Scm[]) { super(...vals); Object.setPrototypeOf(this, Object.create(Scms.prototype)); } static fromJSON(data: ScmJSON[]): Scms { return new Scms(...data.map((a) => Scm.fromJSON(a))); } } class ScmUsage { group: string; pipeline: string; constructor(group: string, pipeline: string) { this.group = group; this.pipeline = pipeline; } static fromJSON(data: ScmUsageJSON): ScmUsage { return new ScmUsage(data.group, data.pipeline); } } export class ScmUsages extends Array<ScmUsage> {
(...vals: ScmUsage[]) { super(...vals); Object.setPrototypeOf(this, Object.create(ScmUsages.prototype)); } static fromJSON(data: ScmUsagesJSON): ScmUsages { return new ScmUsages(...data.usages.map((a) => ScmUsage.fromJSON(a))); } }
constructor
identifier_name
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use std::{collections::BTreeSet, env}; pub mod api; pub mod api_utils; pub mod display_utils; pub mod error; pub mod filesystem; pub mod nginx; pub mod ostpool; pub mod profile; pub mod server; pub mod snapshot; pub mod stratagem; pub mod update_repo_file; pub fn parse_hosts(hosts: &[String]) -> Result<BTreeSet<String>, error::ImlManagerCliError> { let parsed: Vec<BTreeSet<String>> = hosts .iter() .map(|x| hostlist_parser::parse(x)) .collect::<Result<_, _>>()?; let union = parsed .into_iter() .fold(BTreeSet::new(), |acc, h| acc.union(&h).cloned().collect()); Ok(union) } fn exe_name() -> Option<String>
pub fn selfname(suffix: Option<&str>) -> Option<String> { match env::var("CLI_NAME") { Ok(n) => suffix.map(|s| format!("{}-{}", n, s)).or_else(|| Some(n)), Err(_) => exe_name(), } }
{ Some( std::env::current_exe() .ok()? .file_stem()? .to_str()? .to_string(), ) }
identifier_body
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use std::{collections::BTreeSet, env}; pub mod api; pub mod api_utils; pub mod display_utils; pub mod error; pub mod filesystem; pub mod nginx; pub mod ostpool; pub mod profile; pub mod server; pub mod snapshot; pub mod stratagem; pub mod update_repo_file; pub fn parse_hosts(hosts: &[String]) -> Result<BTreeSet<String>, error::ImlManagerCliError> { let parsed: Vec<BTreeSet<String>> = hosts .iter() .map(|x| hostlist_parser::parse(x)) .collect::<Result<_, _>>()?; let union = parsed .into_iter() .fold(BTreeSet::new(), |acc, h| acc.union(&h).cloned().collect()); Ok(union) } fn exe_name() -> Option<String> { Some( std::env::current_exe() .ok()? .file_stem()? .to_str()? .to_string(), ) }
} }
pub fn selfname(suffix: Option<&str>) -> Option<String> { match env::var("CLI_NAME") { Ok(n) => suffix.map(|s| format!("{}-{}", n, s)).or_else(|| Some(n)), Err(_) => exe_name(),
random_line_split
lib.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use std::{collections::BTreeSet, env}; pub mod api; pub mod api_utils; pub mod display_utils; pub mod error; pub mod filesystem; pub mod nginx; pub mod ostpool; pub mod profile; pub mod server; pub mod snapshot; pub mod stratagem; pub mod update_repo_file; pub fn
(hosts: &[String]) -> Result<BTreeSet<String>, error::ImlManagerCliError> { let parsed: Vec<BTreeSet<String>> = hosts .iter() .map(|x| hostlist_parser::parse(x)) .collect::<Result<_, _>>()?; let union = parsed .into_iter() .fold(BTreeSet::new(), |acc, h| acc.union(&h).cloned().collect()); Ok(union) } fn exe_name() -> Option<String> { Some( std::env::current_exe() .ok()? .file_stem()? .to_str()? .to_string(), ) } pub fn selfname(suffix: Option<&str>) -> Option<String> { match env::var("CLI_NAME") { Ok(n) => suffix.map(|s| format!("{}-{}", n, s)).or_else(|| Some(n)), Err(_) => exe_name(), } }
parse_hosts
identifier_name
chip-set.ts
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, forwardRef, Input, OnDestroy, Output, QueryList, ViewEncapsulation } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {merge, Observable, Subject, Subscription} from 'rxjs'; import {startWith, takeUntil} from 'rxjs/operators'; import {MDCComponent} from '@angular-mdc/web/base'; import { MdcChipInteractionEvent, MdcChipNavigationEvent, MdcChipSelectionEvent, MdcChipRemovalEvent } from './chip-config'; import { MdcChip, MDC_CHIPSET_PARENT_COMPONENT } from './chip'; import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips'; /** * Provider Expression that allows mdc-chip-set to register as a ControlValueAccessor. This * allows it to support [(ngModel)] and ngControl. */ export const MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdcChipSet), multi: true }; export class MdcChipSetChange { constructor( public source: MdcChipSet, public value: any) {} } @Component({ selector: 'mdc-chip-set', exportAs: 'mdcChipSet', host: { 'role': 'grid', 'class': 'mdc-chip-set', '[class.mdc-chip-set--choice]': 'choice', '[class.mdc-chip-set--filter]': 'filter', '[class.mdc-chip-set--input]': 'input' }, template: '<ng-content></ng-content>', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [ MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR, {provide: MDC_CHIPSET_PARENT_COMPONENT, useExisting: MdcChipSet} ] }) export class MdcChipSet extends MDCComponent<MDCChipSetFoundation> implements AfterContentInit, OnDestroy, ControlValueAccessor { /** Emits whenever the component is destroyed. */ private _destroyed = new Subject<void>(); /** * Indicates that the chips in the set are choice chips, which allow a single selection from a set of options. */ @Input() get choice(): boolean { return this._choice; } set choice(value: boolean) { this._choice = coerceBooleanProperty(value); } private _choice = false; /** * Indicates that the chips in the set are filter chips, which allow multiple selection from a set of options. */ @Input() get filter(): boolean { return this._filter; } set filter(value: boolean) { this._filter = coerceBooleanProperty(value); } private _filter = false; /** * Indicates that the chips in the set are input chips, which enable user input by converting text into chips. */ @Input() get input(): boolean { return this._input; } set input(value: boolean) { this._input = coerceBooleanProperty(value); } private _input = false; @Input() get value(): string | string[] | undefined { return this._value; } set value(value: string | string[] | undefined) { this._value = value; this.writeValue(value); } private _value?: string | string[]; /** * A function to compare the option values with the selected values. The first argument * is a value from an option. The second is a value from the selection. A boolean * should be returned. */ private _compareWith = (o1: any, o2: any) => o1 === o2; @Output() readonly change: EventEmitter<MdcChipSetChange> = new EventEmitter<MdcChipSetChange>(); @Output() readonly interaction: EventEmitter<MdcChipInteractionEvent> = new EventEmitter<MdcChipInteractionEvent>(); @ContentChildren(MdcChip, {descendants: true}) chips!: QueryList<MdcChip>; /** Function when touched */ _onTouched = () => {}; /** Function when changed */ _onChange: (value: any) => void = () => {}; /** Subscription to selection events in chips. */ private _chipSelectionSubscription: Subscription | null = null; /** Subscription to removal changes. */ private _chipRemovalSubscription: Subscription | null = null; /** Subscription to interaction events in chips. */ private _chipInteractionSubscription: Subscription | null = null; /** Subscription to navigation events. */ private _navigationSubscription: Subscription | null = null; /** Combined stream of all of the chip selection events. */ get chipSelections(): Observable<MdcChipSelectionEvent> { return merge(...this.chips.map(chip => chip.selectionChange)); } /** Combined stream of all of the chip interaction events. */ get chipInteractions(): Observable<MdcChipInteractionEvent> { return merge(...this.chips.map(chip => chip.interactionEvent)); } /** Combined stream of all of the chip removal events. */ get chipRemovalChanges(): Observable<MdcChipRemovalEvent> { return merge(...this.chips.map(chip => chip.removalEvent)); } /** Combined stream of all of the chip navigation events. */ get chipNavigations(): Observable<MdcChipNavigationEvent> { return merge(...this.chips.map(chip => chip.navigationEvent)); } getDefaultFoundation() { const adapter: MDCChipSetAdapter = { hasClass: (className: string) => this._getHostElement().classList.contains(className), focusChipPrimaryActionAtIndex: (index: number) => this.chips.toArray()[index].focusPrimaryAction(), focusChipTrailingActionAtIndex: (index: number) => this.chips.toArray()[index].focusTrailingAction(), getChipListCount: () => this.chips.length, getIndexOfChipById: (chipId: string) => this._findChipIndex(chipId), removeChipAtIndex: (index: number) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].destroy(); this.chips.toArray()[index].remove(); this.chips.toArray().splice(index, 1); } }, removeFocusFromChipAtIndex: (index: number) => this.chips.toArray()[index].removeFocus(), selectChipAtIndex: (index: number, selected: boolean, shouldNotifyClients: boolean) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].setSelectedFromChipSet(selected, shouldNotifyClients); } }, announceMessage: () => {}, isRTL: () => typeof window !== 'undefined' ? window.getComputedStyle(this._getHostElement()).getPropertyValue('direction') === 'rtl' : false }; return new MDCChipSetFoundation(adapter); } constructor( private _changeDetectorRef: ChangeDetectorRef, public elementRef: ElementRef<HTMLElement>) { super(elementRef); } ngAfterContentInit(): void { // When chips change, re-subscribe this.chips.changes.pipe(startWith(null), takeUntil(this._destroyed)) .subscribe(() => { this._resetChipSet(); if (this.chips.length >= 0) { this._initializeSelection(); } }); } ngOnDestroy(): void { this._destroyed.next(); this._destroyed.complete();
this._chipRemovalSubscription?.unsubscribe(); this._foundation?.destroy(); } // Implemented as part of ControlValueAccessor. writeValue(value: any): void { this.selectByValue(value, true); } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => void): void { this._onChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: () => void): void { this._onTouched = fn; } getSelectedChipIds(): ReadonlyArray<string> { return this._foundation.getSelectedChipIds(); } select(chipId: string): void { this._foundation.select(chipId); } selectByValue(value: string | string[] | undefined, shouldIgnore = true): void { if (!this.chips) { return; } if (Array.isArray(value)) { value.forEach(currentValue => this._selectValue(currentValue, shouldIgnore)); } else { this._selectValue(value, shouldIgnore); } this._value = value; } /** * Finds and selects the chip based on its value. * @returns Chip that has the corresponding value. */ private _selectValue(value: any, shouldIgnore = true): MdcChip | undefined { const correspondingChip = this.chips.find(chip => chip.value != null && this._compareWith(chip.value, value)); if (correspondingChip) { if (this.choice) { this.select(correspondingChip.id); } else { correspondingChip.setSelectedFromChipSet(true, shouldIgnore); } } return correspondingChip; } private _initializeSelection(): void { // Defer setting the value in order to avoid the "Expression // has changed after it was checked" errors from Angular. Promise.resolve().then(() => { if (this._value) { this.selectByValue(this._value, false); } }); } private _propagateChanges(evt: MdcChipSelectionEvent): void { this._value = evt.value; this.change.emit(new MdcChipSetChange(this, evt)); this._onChange(this._value); this._changeDetectorRef.markForCheck(); } private _findChipIndex(chipId: string): number { return this.chips.toArray().findIndex(_ => _.id === chipId); } private _resetChipSet(): void { this._dropSubscriptions(); this._listenToChipEvents(); } private _dropSubscriptions(): void { this._chipSelectionSubscription?.unsubscribe(); this._chipInteractionSubscription?.unsubscribe(); this._chipRemovalSubscription?.unsubscribe(); this._navigationSubscription?.unsubscribe(); } /** Listens to selected events on each chip. */ private _listenToChipEvents(): void { this._chipSelectionSubscription = this.chipSelections .subscribe((event: MdcChipSelectionEvent) => { this._foundation.handleChipSelection(event); this._propagateChanges(event); }); this._chipInteractionSubscription = this.chipInteractions .subscribe((event: MdcChipInteractionEvent) => { this._foundation.handleChipInteraction(event); this.interaction.emit(event); }); this._chipRemovalSubscription = this.chipRemovalChanges .subscribe((event: MdcChipRemovalEvent) => this._foundation.handleChipRemoval(event)); this._navigationSubscription = this.chipNavigations .subscribe((event: MdcChipNavigationEvent) => this._foundation.handleChipNavigation(event)); } /** Retrieves the DOM element of the component host. */ private _getHostElement(): HTMLElement { return this.elementRef.nativeElement; } }
this._dropSubscriptions();
random_line_split
chip-set.ts
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, forwardRef, Input, OnDestroy, Output, QueryList, ViewEncapsulation } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {merge, Observable, Subject, Subscription} from 'rxjs'; import {startWith, takeUntil} from 'rxjs/operators'; import {MDCComponent} from '@angular-mdc/web/base'; import { MdcChipInteractionEvent, MdcChipNavigationEvent, MdcChipSelectionEvent, MdcChipRemovalEvent } from './chip-config'; import { MdcChip, MDC_CHIPSET_PARENT_COMPONENT } from './chip'; import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips'; /** * Provider Expression that allows mdc-chip-set to register as a ControlValueAccessor. This * allows it to support [(ngModel)] and ngControl. */ export const MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdcChipSet), multi: true }; export class MdcChipSetChange { constructor( public source: MdcChipSet, public value: any) {} } @Component({ selector: 'mdc-chip-set', exportAs: 'mdcChipSet', host: { 'role': 'grid', 'class': 'mdc-chip-set', '[class.mdc-chip-set--choice]': 'choice', '[class.mdc-chip-set--filter]': 'filter', '[class.mdc-chip-set--input]': 'input' }, template: '<ng-content></ng-content>', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [ MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR, {provide: MDC_CHIPSET_PARENT_COMPONENT, useExisting: MdcChipSet} ] }) export class MdcChipSet extends MDCComponent<MDCChipSetFoundation> implements AfterContentInit, OnDestroy, ControlValueAccessor { /** Emits whenever the component is destroyed. */ private _destroyed = new Subject<void>(); /** * Indicates that the chips in the set are choice chips, which allow a single selection from a set of options. */ @Input() get choice(): boolean { return this._choice; } set choice(value: boolean) { this._choice = coerceBooleanProperty(value); } private _choice = false; /** * Indicates that the chips in the set are filter chips, which allow multiple selection from a set of options. */ @Input() get filter(): boolean { return this._filter; } set filter(value: boolean) { this._filter = coerceBooleanProperty(value); } private _filter = false; /** * Indicates that the chips in the set are input chips, which enable user input by converting text into chips. */ @Input() get input(): boolean
set input(value: boolean) { this._input = coerceBooleanProperty(value); } private _input = false; @Input() get value(): string | string[] | undefined { return this._value; } set value(value: string | string[] | undefined) { this._value = value; this.writeValue(value); } private _value?: string | string[]; /** * A function to compare the option values with the selected values. The first argument * is a value from an option. The second is a value from the selection. A boolean * should be returned. */ private _compareWith = (o1: any, o2: any) => o1 === o2; @Output() readonly change: EventEmitter<MdcChipSetChange> = new EventEmitter<MdcChipSetChange>(); @Output() readonly interaction: EventEmitter<MdcChipInteractionEvent> = new EventEmitter<MdcChipInteractionEvent>(); @ContentChildren(MdcChip, {descendants: true}) chips!: QueryList<MdcChip>; /** Function when touched */ _onTouched = () => {}; /** Function when changed */ _onChange: (value: any) => void = () => {}; /** Subscription to selection events in chips. */ private _chipSelectionSubscription: Subscription | null = null; /** Subscription to removal changes. */ private _chipRemovalSubscription: Subscription | null = null; /** Subscription to interaction events in chips. */ private _chipInteractionSubscription: Subscription | null = null; /** Subscription to navigation events. */ private _navigationSubscription: Subscription | null = null; /** Combined stream of all of the chip selection events. */ get chipSelections(): Observable<MdcChipSelectionEvent> { return merge(...this.chips.map(chip => chip.selectionChange)); } /** Combined stream of all of the chip interaction events. */ get chipInteractions(): Observable<MdcChipInteractionEvent> { return merge(...this.chips.map(chip => chip.interactionEvent)); } /** Combined stream of all of the chip removal events. */ get chipRemovalChanges(): Observable<MdcChipRemovalEvent> { return merge(...this.chips.map(chip => chip.removalEvent)); } /** Combined stream of all of the chip navigation events. */ get chipNavigations(): Observable<MdcChipNavigationEvent> { return merge(...this.chips.map(chip => chip.navigationEvent)); } getDefaultFoundation() { const adapter: MDCChipSetAdapter = { hasClass: (className: string) => this._getHostElement().classList.contains(className), focusChipPrimaryActionAtIndex: (index: number) => this.chips.toArray()[index].focusPrimaryAction(), focusChipTrailingActionAtIndex: (index: number) => this.chips.toArray()[index].focusTrailingAction(), getChipListCount: () => this.chips.length, getIndexOfChipById: (chipId: string) => this._findChipIndex(chipId), removeChipAtIndex: (index: number) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].destroy(); this.chips.toArray()[index].remove(); this.chips.toArray().splice(index, 1); } }, removeFocusFromChipAtIndex: (index: number) => this.chips.toArray()[index].removeFocus(), selectChipAtIndex: (index: number, selected: boolean, shouldNotifyClients: boolean) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].setSelectedFromChipSet(selected, shouldNotifyClients); } }, announceMessage: () => {}, isRTL: () => typeof window !== 'undefined' ? window.getComputedStyle(this._getHostElement()).getPropertyValue('direction') === 'rtl' : false }; return new MDCChipSetFoundation(adapter); } constructor( private _changeDetectorRef: ChangeDetectorRef, public elementRef: ElementRef<HTMLElement>) { super(elementRef); } ngAfterContentInit(): void { // When chips change, re-subscribe this.chips.changes.pipe(startWith(null), takeUntil(this._destroyed)) .subscribe(() => { this._resetChipSet(); if (this.chips.length >= 0) { this._initializeSelection(); } }); } ngOnDestroy(): void { this._destroyed.next(); this._destroyed.complete(); this._dropSubscriptions(); this._chipRemovalSubscription?.unsubscribe(); this._foundation?.destroy(); } // Implemented as part of ControlValueAccessor. writeValue(value: any): void { this.selectByValue(value, true); } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => void): void { this._onChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: () => void): void { this._onTouched = fn; } getSelectedChipIds(): ReadonlyArray<string> { return this._foundation.getSelectedChipIds(); } select(chipId: string): void { this._foundation.select(chipId); } selectByValue(value: string | string[] | undefined, shouldIgnore = true): void { if (!this.chips) { return; } if (Array.isArray(value)) { value.forEach(currentValue => this._selectValue(currentValue, shouldIgnore)); } else { this._selectValue(value, shouldIgnore); } this._value = value; } /** * Finds and selects the chip based on its value. * @returns Chip that has the corresponding value. */ private _selectValue(value: any, shouldIgnore = true): MdcChip | undefined { const correspondingChip = this.chips.find(chip => chip.value != null && this._compareWith(chip.value, value)); if (correspondingChip) { if (this.choice) { this.select(correspondingChip.id); } else { correspondingChip.setSelectedFromChipSet(true, shouldIgnore); } } return correspondingChip; } private _initializeSelection(): void { // Defer setting the value in order to avoid the "Expression // has changed after it was checked" errors from Angular. Promise.resolve().then(() => { if (this._value) { this.selectByValue(this._value, false); } }); } private _propagateChanges(evt: MdcChipSelectionEvent): void { this._value = evt.value; this.change.emit(new MdcChipSetChange(this, evt)); this._onChange(this._value); this._changeDetectorRef.markForCheck(); } private _findChipIndex(chipId: string): number { return this.chips.toArray().findIndex(_ => _.id === chipId); } private _resetChipSet(): void { this._dropSubscriptions(); this._listenToChipEvents(); } private _dropSubscriptions(): void { this._chipSelectionSubscription?.unsubscribe(); this._chipInteractionSubscription?.unsubscribe(); this._chipRemovalSubscription?.unsubscribe(); this._navigationSubscription?.unsubscribe(); } /** Listens to selected events on each chip. */ private _listenToChipEvents(): void { this._chipSelectionSubscription = this.chipSelections .subscribe((event: MdcChipSelectionEvent) => { this._foundation.handleChipSelection(event); this._propagateChanges(event); }); this._chipInteractionSubscription = this.chipInteractions .subscribe((event: MdcChipInteractionEvent) => { this._foundation.handleChipInteraction(event); this.interaction.emit(event); }); this._chipRemovalSubscription = this.chipRemovalChanges .subscribe((event: MdcChipRemovalEvent) => this._foundation.handleChipRemoval(event)); this._navigationSubscription = this.chipNavigations .subscribe((event: MdcChipNavigationEvent) => this._foundation.handleChipNavigation(event)); } /** Retrieves the DOM element of the component host. */ private _getHostElement(): HTMLElement { return this.elementRef.nativeElement; } }
{ return this._input; }
identifier_body
chip-set.ts
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, forwardRef, Input, OnDestroy, Output, QueryList, ViewEncapsulation } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {merge, Observable, Subject, Subscription} from 'rxjs'; import {startWith, takeUntil} from 'rxjs/operators'; import {MDCComponent} from '@angular-mdc/web/base'; import { MdcChipInteractionEvent, MdcChipNavigationEvent, MdcChipSelectionEvent, MdcChipRemovalEvent } from './chip-config'; import { MdcChip, MDC_CHIPSET_PARENT_COMPONENT } from './chip'; import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips'; /** * Provider Expression that allows mdc-chip-set to register as a ControlValueAccessor. This * allows it to support [(ngModel)] and ngControl. */ export const MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdcChipSet), multi: true }; export class MdcChipSetChange { constructor( public source: MdcChipSet, public value: any) {} } @Component({ selector: 'mdc-chip-set', exportAs: 'mdcChipSet', host: { 'role': 'grid', 'class': 'mdc-chip-set', '[class.mdc-chip-set--choice]': 'choice', '[class.mdc-chip-set--filter]': 'filter', '[class.mdc-chip-set--input]': 'input' }, template: '<ng-content></ng-content>', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [ MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR, {provide: MDC_CHIPSET_PARENT_COMPONENT, useExisting: MdcChipSet} ] }) export class MdcChipSet extends MDCComponent<MDCChipSetFoundation> implements AfterContentInit, OnDestroy, ControlValueAccessor { /** Emits whenever the component is destroyed. */ private _destroyed = new Subject<void>(); /** * Indicates that the chips in the set are choice chips, which allow a single selection from a set of options. */ @Input() get choice(): boolean { return this._choice; } set choice(value: boolean) { this._choice = coerceBooleanProperty(value); } private _choice = false; /** * Indicates that the chips in the set are filter chips, which allow multiple selection from a set of options. */ @Input() get filter(): boolean { return this._filter; } set filter(value: boolean) { this._filter = coerceBooleanProperty(value); } private _filter = false; /** * Indicates that the chips in the set are input chips, which enable user input by converting text into chips. */ @Input() get input(): boolean { return this._input; } set input(value: boolean) { this._input = coerceBooleanProperty(value); } private _input = false; @Input() get value(): string | string[] | undefined { return this._value; } set value(value: string | string[] | undefined) { this._value = value; this.writeValue(value); } private _value?: string | string[]; /** * A function to compare the option values with the selected values. The first argument * is a value from an option. The second is a value from the selection. A boolean * should be returned. */ private _compareWith = (o1: any, o2: any) => o1 === o2; @Output() readonly change: EventEmitter<MdcChipSetChange> = new EventEmitter<MdcChipSetChange>(); @Output() readonly interaction: EventEmitter<MdcChipInteractionEvent> = new EventEmitter<MdcChipInteractionEvent>(); @ContentChildren(MdcChip, {descendants: true}) chips!: QueryList<MdcChip>; /** Function when touched */ _onTouched = () => {}; /** Function when changed */ _onChange: (value: any) => void = () => {}; /** Subscription to selection events in chips. */ private _chipSelectionSubscription: Subscription | null = null; /** Subscription to removal changes. */ private _chipRemovalSubscription: Subscription | null = null; /** Subscription to interaction events in chips. */ private _chipInteractionSubscription: Subscription | null = null; /** Subscription to navigation events. */ private _navigationSubscription: Subscription | null = null; /** Combined stream of all of the chip selection events. */ get chipSelections(): Observable<MdcChipSelectionEvent> { return merge(...this.chips.map(chip => chip.selectionChange)); } /** Combined stream of all of the chip interaction events. */ get chipInteractions(): Observable<MdcChipInteractionEvent> { return merge(...this.chips.map(chip => chip.interactionEvent)); } /** Combined stream of all of the chip removal events. */ get chipRemovalChanges(): Observable<MdcChipRemovalEvent> { return merge(...this.chips.map(chip => chip.removalEvent)); } /** Combined stream of all of the chip navigation events. */ get chipNavigations(): Observable<MdcChipNavigationEvent> { return merge(...this.chips.map(chip => chip.navigationEvent)); } getDefaultFoundation() { const adapter: MDCChipSetAdapter = { hasClass: (className: string) => this._getHostElement().classList.contains(className), focusChipPrimaryActionAtIndex: (index: number) => this.chips.toArray()[index].focusPrimaryAction(), focusChipTrailingActionAtIndex: (index: number) => this.chips.toArray()[index].focusTrailingAction(), getChipListCount: () => this.chips.length, getIndexOfChipById: (chipId: string) => this._findChipIndex(chipId), removeChipAtIndex: (index: number) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].destroy(); this.chips.toArray()[index].remove(); this.chips.toArray().splice(index, 1); } }, removeFocusFromChipAtIndex: (index: number) => this.chips.toArray()[index].removeFocus(), selectChipAtIndex: (index: number, selected: boolean, shouldNotifyClients: boolean) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].setSelectedFromChipSet(selected, shouldNotifyClients); } }, announceMessage: () => {}, isRTL: () => typeof window !== 'undefined' ? window.getComputedStyle(this._getHostElement()).getPropertyValue('direction') === 'rtl' : false }; return new MDCChipSetFoundation(adapter); } constructor( private _changeDetectorRef: ChangeDetectorRef, public elementRef: ElementRef<HTMLElement>) { super(elementRef); } ngAfterContentInit(): void { // When chips change, re-subscribe this.chips.changes.pipe(startWith(null), takeUntil(this._destroyed)) .subscribe(() => { this._resetChipSet(); if (this.chips.length >= 0) { this._initializeSelection(); } }); } ngOnDestroy(): void { this._destroyed.next(); this._destroyed.complete(); this._dropSubscriptions(); this._chipRemovalSubscription?.unsubscribe(); this._foundation?.destroy(); } // Implemented as part of ControlValueAccessor. writeValue(value: any): void { this.selectByValue(value, true); } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => void): void { this._onChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: () => void): void { this._onTouched = fn; } getSelectedChipIds(): ReadonlyArray<string> { return this._foundation.getSelectedChipIds(); } select(chipId: string): void { this._foundation.select(chipId); } selectByValue(value: string | string[] | undefined, shouldIgnore = true): void { if (!this.chips)
if (Array.isArray(value)) { value.forEach(currentValue => this._selectValue(currentValue, shouldIgnore)); } else { this._selectValue(value, shouldIgnore); } this._value = value; } /** * Finds and selects the chip based on its value. * @returns Chip that has the corresponding value. */ private _selectValue(value: any, shouldIgnore = true): MdcChip | undefined { const correspondingChip = this.chips.find(chip => chip.value != null && this._compareWith(chip.value, value)); if (correspondingChip) { if (this.choice) { this.select(correspondingChip.id); } else { correspondingChip.setSelectedFromChipSet(true, shouldIgnore); } } return correspondingChip; } private _initializeSelection(): void { // Defer setting the value in order to avoid the "Expression // has changed after it was checked" errors from Angular. Promise.resolve().then(() => { if (this._value) { this.selectByValue(this._value, false); } }); } private _propagateChanges(evt: MdcChipSelectionEvent): void { this._value = evt.value; this.change.emit(new MdcChipSetChange(this, evt)); this._onChange(this._value); this._changeDetectorRef.markForCheck(); } private _findChipIndex(chipId: string): number { return this.chips.toArray().findIndex(_ => _.id === chipId); } private _resetChipSet(): void { this._dropSubscriptions(); this._listenToChipEvents(); } private _dropSubscriptions(): void { this._chipSelectionSubscription?.unsubscribe(); this._chipInteractionSubscription?.unsubscribe(); this._chipRemovalSubscription?.unsubscribe(); this._navigationSubscription?.unsubscribe(); } /** Listens to selected events on each chip. */ private _listenToChipEvents(): void { this._chipSelectionSubscription = this.chipSelections .subscribe((event: MdcChipSelectionEvent) => { this._foundation.handleChipSelection(event); this._propagateChanges(event); }); this._chipInteractionSubscription = this.chipInteractions .subscribe((event: MdcChipInteractionEvent) => { this._foundation.handleChipInteraction(event); this.interaction.emit(event); }); this._chipRemovalSubscription = this.chipRemovalChanges .subscribe((event: MdcChipRemovalEvent) => this._foundation.handleChipRemoval(event)); this._navigationSubscription = this.chipNavigations .subscribe((event: MdcChipNavigationEvent) => this._foundation.handleChipNavigation(event)); } /** Retrieves the DOM element of the component host. */ private _getHostElement(): HTMLElement { return this.elementRef.nativeElement; } }
{ return; }
conditional_block
chip-set.ts
import { AfterContentInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChildren, ElementRef, EventEmitter, forwardRef, Input, OnDestroy, Output, QueryList, ViewEncapsulation } from '@angular/core'; import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms'; import {coerceBooleanProperty} from '@angular/cdk/coercion'; import {merge, Observable, Subject, Subscription} from 'rxjs'; import {startWith, takeUntil} from 'rxjs/operators'; import {MDCComponent} from '@angular-mdc/web/base'; import { MdcChipInteractionEvent, MdcChipNavigationEvent, MdcChipSelectionEvent, MdcChipRemovalEvent } from './chip-config'; import { MdcChip, MDC_CHIPSET_PARENT_COMPONENT } from './chip'; import {MDCChipSetFoundation, MDCChipSetAdapter} from '@material/chips'; /** * Provider Expression that allows mdc-chip-set to register as a ControlValueAccessor. This * allows it to support [(ngModel)] and ngControl. */ export const MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR: any = { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => MdcChipSet), multi: true }; export class MdcChipSetChange { constructor( public source: MdcChipSet, public value: any) {} } @Component({ selector: 'mdc-chip-set', exportAs: 'mdcChipSet', host: { 'role': 'grid', 'class': 'mdc-chip-set', '[class.mdc-chip-set--choice]': 'choice', '[class.mdc-chip-set--filter]': 'filter', '[class.mdc-chip-set--input]': 'input' }, template: '<ng-content></ng-content>', encapsulation: ViewEncapsulation.None, changeDetection: ChangeDetectionStrategy.OnPush, providers: [ MDC_CHIP_SET_CONTROL_VALUE_ACCESSOR, {provide: MDC_CHIPSET_PARENT_COMPONENT, useExisting: MdcChipSet} ] }) export class MdcChipSet extends MDCComponent<MDCChipSetFoundation> implements AfterContentInit, OnDestroy, ControlValueAccessor { /** Emits whenever the component is destroyed. */ private _destroyed = new Subject<void>(); /** * Indicates that the chips in the set are choice chips, which allow a single selection from a set of options. */ @Input() get choice(): boolean { return this._choice; } set choice(value: boolean) { this._choice = coerceBooleanProperty(value); } private _choice = false; /** * Indicates that the chips in the set are filter chips, which allow multiple selection from a set of options. */ @Input() get filter(): boolean { return this._filter; } set filter(value: boolean) { this._filter = coerceBooleanProperty(value); } private _filter = false; /** * Indicates that the chips in the set are input chips, which enable user input by converting text into chips. */ @Input() get input(): boolean { return this._input; } set input(value: boolean) { this._input = coerceBooleanProperty(value); } private _input = false; @Input() get value(): string | string[] | undefined { return this._value; } set value(value: string | string[] | undefined) { this._value = value; this.writeValue(value); } private _value?: string | string[]; /** * A function to compare the option values with the selected values. The first argument * is a value from an option. The second is a value from the selection. A boolean * should be returned. */ private _compareWith = (o1: any, o2: any) => o1 === o2; @Output() readonly change: EventEmitter<MdcChipSetChange> = new EventEmitter<MdcChipSetChange>(); @Output() readonly interaction: EventEmitter<MdcChipInteractionEvent> = new EventEmitter<MdcChipInteractionEvent>(); @ContentChildren(MdcChip, {descendants: true}) chips!: QueryList<MdcChip>; /** Function when touched */ _onTouched = () => {}; /** Function when changed */ _onChange: (value: any) => void = () => {}; /** Subscription to selection events in chips. */ private _chipSelectionSubscription: Subscription | null = null; /** Subscription to removal changes. */ private _chipRemovalSubscription: Subscription | null = null; /** Subscription to interaction events in chips. */ private _chipInteractionSubscription: Subscription | null = null; /** Subscription to navigation events. */ private _navigationSubscription: Subscription | null = null; /** Combined stream of all of the chip selection events. */ get chipSelections(): Observable<MdcChipSelectionEvent> { return merge(...this.chips.map(chip => chip.selectionChange)); } /** Combined stream of all of the chip interaction events. */ get chipInteractions(): Observable<MdcChipInteractionEvent> { return merge(...this.chips.map(chip => chip.interactionEvent)); } /** Combined stream of all of the chip removal events. */ get chipRemovalChanges(): Observable<MdcChipRemovalEvent> { return merge(...this.chips.map(chip => chip.removalEvent)); } /** Combined stream of all of the chip navigation events. */ get chipNavigations(): Observable<MdcChipNavigationEvent> { return merge(...this.chips.map(chip => chip.navigationEvent)); } getDefaultFoundation() { const adapter: MDCChipSetAdapter = { hasClass: (className: string) => this._getHostElement().classList.contains(className), focusChipPrimaryActionAtIndex: (index: number) => this.chips.toArray()[index].focusPrimaryAction(), focusChipTrailingActionAtIndex: (index: number) => this.chips.toArray()[index].focusTrailingAction(), getChipListCount: () => this.chips.length, getIndexOfChipById: (chipId: string) => this._findChipIndex(chipId), removeChipAtIndex: (index: number) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].destroy(); this.chips.toArray()[index].remove(); this.chips.toArray().splice(index, 1); } }, removeFocusFromChipAtIndex: (index: number) => this.chips.toArray()[index].removeFocus(), selectChipAtIndex: (index: number, selected: boolean, shouldNotifyClients: boolean) => { if (index >= 0 && index < this.chips.length) { this.chips.toArray()[index].setSelectedFromChipSet(selected, shouldNotifyClients); } }, announceMessage: () => {}, isRTL: () => typeof window !== 'undefined' ? window.getComputedStyle(this._getHostElement()).getPropertyValue('direction') === 'rtl' : false }; return new MDCChipSetFoundation(adapter); } constructor( private _changeDetectorRef: ChangeDetectorRef, public elementRef: ElementRef<HTMLElement>) { super(elementRef); } ngAfterContentInit(): void { // When chips change, re-subscribe this.chips.changes.pipe(startWith(null), takeUntil(this._destroyed)) .subscribe(() => { this._resetChipSet(); if (this.chips.length >= 0) { this._initializeSelection(); } }); } ngOnDestroy(): void { this._destroyed.next(); this._destroyed.complete(); this._dropSubscriptions(); this._chipRemovalSubscription?.unsubscribe(); this._foundation?.destroy(); } // Implemented as part of ControlValueAccessor. writeValue(value: any): void { this.selectByValue(value, true); } // Implemented as part of ControlValueAccessor. registerOnChange(fn: (value: any) => void): void { this._onChange = fn; } // Implemented as part of ControlValueAccessor. registerOnTouched(fn: () => void): void { this._onTouched = fn; }
(): ReadonlyArray<string> { return this._foundation.getSelectedChipIds(); } select(chipId: string): void { this._foundation.select(chipId); } selectByValue(value: string | string[] | undefined, shouldIgnore = true): void { if (!this.chips) { return; } if (Array.isArray(value)) { value.forEach(currentValue => this._selectValue(currentValue, shouldIgnore)); } else { this._selectValue(value, shouldIgnore); } this._value = value; } /** * Finds and selects the chip based on its value. * @returns Chip that has the corresponding value. */ private _selectValue(value: any, shouldIgnore = true): MdcChip | undefined { const correspondingChip = this.chips.find(chip => chip.value != null && this._compareWith(chip.value, value)); if (correspondingChip) { if (this.choice) { this.select(correspondingChip.id); } else { correspondingChip.setSelectedFromChipSet(true, shouldIgnore); } } return correspondingChip; } private _initializeSelection(): void { // Defer setting the value in order to avoid the "Expression // has changed after it was checked" errors from Angular. Promise.resolve().then(() => { if (this._value) { this.selectByValue(this._value, false); } }); } private _propagateChanges(evt: MdcChipSelectionEvent): void { this._value = evt.value; this.change.emit(new MdcChipSetChange(this, evt)); this._onChange(this._value); this._changeDetectorRef.markForCheck(); } private _findChipIndex(chipId: string): number { return this.chips.toArray().findIndex(_ => _.id === chipId); } private _resetChipSet(): void { this._dropSubscriptions(); this._listenToChipEvents(); } private _dropSubscriptions(): void { this._chipSelectionSubscription?.unsubscribe(); this._chipInteractionSubscription?.unsubscribe(); this._chipRemovalSubscription?.unsubscribe(); this._navigationSubscription?.unsubscribe(); } /** Listens to selected events on each chip. */ private _listenToChipEvents(): void { this._chipSelectionSubscription = this.chipSelections .subscribe((event: MdcChipSelectionEvent) => { this._foundation.handleChipSelection(event); this._propagateChanges(event); }); this._chipInteractionSubscription = this.chipInteractions .subscribe((event: MdcChipInteractionEvent) => { this._foundation.handleChipInteraction(event); this.interaction.emit(event); }); this._chipRemovalSubscription = this.chipRemovalChanges .subscribe((event: MdcChipRemovalEvent) => this._foundation.handleChipRemoval(event)); this._navigationSubscription = this.chipNavigations .subscribe((event: MdcChipNavigationEvent) => this._foundation.handleChipNavigation(event)); } /** Retrieves the DOM element of the component host. */ private _getHostElement(): HTMLElement { return this.elementRef.nativeElement; } }
getSelectedChipIds
identifier_name
osl.py
# # Copyright 2011-2013 Blender Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # <pep8 compliant> import bpy import _cycles def osl_compile(input_path, report): """compile .osl file with given filepath to temporary .oso file""" import tempfile output_file = tempfile.NamedTemporaryFile(mode='w', suffix=".oso", delete=False) output_path = output_file.name output_file.close() ok = _cycles.osl_compile(input_path, output_path) if ok: report({'INFO'}, "OSL shader compilation succeeded") return ok, output_path def update_script_node(node, report): """compile and update shader script node""" import os import shutil import tempfile if node.mode == 'EXTERNAL': # compile external script file script_path = bpy.path.abspath(node.filepath, library=node.id_data.library) script_path_noext, script_ext = os.path.splitext(script_path) if script_ext == ".oso": # it's a .oso file, no need to compile ok, oso_path = True, script_path oso_file_remove = False elif script_ext == ".osl": # compile .osl file ok, oso_path = osl_compile(script_path, report) oso_file_remove = True if ok: # copy .oso from temporary path to .osl directory dst_path = script_path_noext + ".oso" try: shutil.copy2(oso_path, dst_path) except: report({'ERROR'}, "Failed to write .oso file next to external .osl file at " + dst_path) elif os.path.dirname(node.filepath) == "": # module in search path oso_path = node.filepath oso_file_remove = False ok = True else: # unknown report({'ERROR'}, "External shader script must have .osl or .oso extension, or be a module name") ok = False if ok: node.bytecode = "" node.bytecode_hash = "" elif node.mode == 'INTERNAL' and node.script: # internal script, we will store bytecode in the node script = node.script osl_path = bpy.path.abspath(script.filepath, library=script.library) if script.is_in_memory or script.is_dirty or script.is_modified or not os.path.exists(osl_path): # write text datablock contents to temporary file osl_file = tempfile.NamedTemporaryFile(mode='w', suffix=".osl", delete=False) osl_file.write(script.as_string()) osl_file.close() ok, oso_path = osl_compile(osl_file.name, report) oso_file_remove = False os.remove(osl_file.name) else: # compile text datablock from disk directly
if ok: # read bytecode try: oso = open(oso_path, 'r') node.bytecode = oso.read() oso.close() except: import traceback traceback.print_exc() report({'ERROR'}, "Can't read OSO bytecode to store in node at %r" % oso_path) ok = False else: report({'WARNING'}, "No text or file specified in node, nothing to compile") return if ok: # now update node with new sockets ok = _cycles.osl_update_node(node.id_data.as_pointer(), node.as_pointer(), oso_path) if not ok: report({'ERROR'}, "OSL query failed to open " + oso_path) else: report({'ERROR'}, "OSL script compilation failed, see console for errors") # remove temporary oso file if oso_file_remove: try: os.remove(oso_path) except: pass return ok
ok, oso_path = osl_compile(osl_path, report) oso_file_remove = False
conditional_block
osl.py
# # Copyright 2011-2013 Blender Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # <pep8 compliant> import bpy import _cycles def osl_compile(input_path, report): """compile .osl file with given filepath to temporary .oso file""" import tempfile output_file = tempfile.NamedTemporaryFile(mode='w', suffix=".oso", delete=False) output_path = output_file.name output_file.close() ok = _cycles.osl_compile(input_path, output_path) if ok: report({'INFO'}, "OSL shader compilation succeeded") return ok, output_path def update_script_node(node, report):
"""compile and update shader script node""" import os import shutil import tempfile if node.mode == 'EXTERNAL': # compile external script file script_path = bpy.path.abspath(node.filepath, library=node.id_data.library) script_path_noext, script_ext = os.path.splitext(script_path) if script_ext == ".oso": # it's a .oso file, no need to compile ok, oso_path = True, script_path oso_file_remove = False elif script_ext == ".osl": # compile .osl file ok, oso_path = osl_compile(script_path, report) oso_file_remove = True if ok: # copy .oso from temporary path to .osl directory dst_path = script_path_noext + ".oso" try: shutil.copy2(oso_path, dst_path) except: report({'ERROR'}, "Failed to write .oso file next to external .osl file at " + dst_path) elif os.path.dirname(node.filepath) == "": # module in search path oso_path = node.filepath oso_file_remove = False ok = True else: # unknown report({'ERROR'}, "External shader script must have .osl or .oso extension, or be a module name") ok = False if ok: node.bytecode = "" node.bytecode_hash = "" elif node.mode == 'INTERNAL' and node.script: # internal script, we will store bytecode in the node script = node.script osl_path = bpy.path.abspath(script.filepath, library=script.library) if script.is_in_memory or script.is_dirty or script.is_modified or not os.path.exists(osl_path): # write text datablock contents to temporary file osl_file = tempfile.NamedTemporaryFile(mode='w', suffix=".osl", delete=False) osl_file.write(script.as_string()) osl_file.close() ok, oso_path = osl_compile(osl_file.name, report) oso_file_remove = False os.remove(osl_file.name) else: # compile text datablock from disk directly ok, oso_path = osl_compile(osl_path, report) oso_file_remove = False if ok: # read bytecode try: oso = open(oso_path, 'r') node.bytecode = oso.read() oso.close() except: import traceback traceback.print_exc() report({'ERROR'}, "Can't read OSO bytecode to store in node at %r" % oso_path) ok = False else: report({'WARNING'}, "No text or file specified in node, nothing to compile") return if ok: # now update node with new sockets ok = _cycles.osl_update_node(node.id_data.as_pointer(), node.as_pointer(), oso_path) if not ok: report({'ERROR'}, "OSL query failed to open " + oso_path) else: report({'ERROR'}, "OSL script compilation failed, see console for errors") # remove temporary oso file if oso_file_remove: try: os.remove(oso_path) except: pass return ok
identifier_body
osl.py
# # Copyright 2011-2013 Blender Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # <pep8 compliant> import bpy import _cycles def osl_compile(input_path, report): """compile .osl file with given filepath to temporary .oso file""" import tempfile output_file = tempfile.NamedTemporaryFile(mode='w', suffix=".oso", delete=False) output_path = output_file.name output_file.close() ok = _cycles.osl_compile(input_path, output_path) if ok: report({'INFO'}, "OSL shader compilation succeeded") return ok, output_path def
(node, report): """compile and update shader script node""" import os import shutil import tempfile if node.mode == 'EXTERNAL': # compile external script file script_path = bpy.path.abspath(node.filepath, library=node.id_data.library) script_path_noext, script_ext = os.path.splitext(script_path) if script_ext == ".oso": # it's a .oso file, no need to compile ok, oso_path = True, script_path oso_file_remove = False elif script_ext == ".osl": # compile .osl file ok, oso_path = osl_compile(script_path, report) oso_file_remove = True if ok: # copy .oso from temporary path to .osl directory dst_path = script_path_noext + ".oso" try: shutil.copy2(oso_path, dst_path) except: report({'ERROR'}, "Failed to write .oso file next to external .osl file at " + dst_path) elif os.path.dirname(node.filepath) == "": # module in search path oso_path = node.filepath oso_file_remove = False ok = True else: # unknown report({'ERROR'}, "External shader script must have .osl or .oso extension, or be a module name") ok = False if ok: node.bytecode = "" node.bytecode_hash = "" elif node.mode == 'INTERNAL' and node.script: # internal script, we will store bytecode in the node script = node.script osl_path = bpy.path.abspath(script.filepath, library=script.library) if script.is_in_memory or script.is_dirty or script.is_modified or not os.path.exists(osl_path): # write text datablock contents to temporary file osl_file = tempfile.NamedTemporaryFile(mode='w', suffix=".osl", delete=False) osl_file.write(script.as_string()) osl_file.close() ok, oso_path = osl_compile(osl_file.name, report) oso_file_remove = False os.remove(osl_file.name) else: # compile text datablock from disk directly ok, oso_path = osl_compile(osl_path, report) oso_file_remove = False if ok: # read bytecode try: oso = open(oso_path, 'r') node.bytecode = oso.read() oso.close() except: import traceback traceback.print_exc() report({'ERROR'}, "Can't read OSO bytecode to store in node at %r" % oso_path) ok = False else: report({'WARNING'}, "No text or file specified in node, nothing to compile") return if ok: # now update node with new sockets ok = _cycles.osl_update_node(node.id_data.as_pointer(), node.as_pointer(), oso_path) if not ok: report({'ERROR'}, "OSL query failed to open " + oso_path) else: report({'ERROR'}, "OSL script compilation failed, see console for errors") # remove temporary oso file if oso_file_remove: try: os.remove(oso_path) except: pass return ok
update_script_node
identifier_name
osl.py
# # Copyright 2011-2013 Blender Foundation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # <pep8 compliant> import bpy import _cycles def osl_compile(input_path, report): """compile .osl file with given filepath to temporary .oso file""" import tempfile output_file = tempfile.NamedTemporaryFile(mode='w', suffix=".oso", delete=False) output_path = output_file.name output_file.close() ok = _cycles.osl_compile(input_path, output_path) if ok: report({'INFO'}, "OSL shader compilation succeeded") return ok, output_path def update_script_node(node, report): """compile and update shader script node""" import os import shutil import tempfile if node.mode == 'EXTERNAL': # compile external script file script_path = bpy.path.abspath(node.filepath, library=node.id_data.library) script_path_noext, script_ext = os.path.splitext(script_path) if script_ext == ".oso": # it's a .oso file, no need to compile ok, oso_path = True, script_path oso_file_remove = False elif script_ext == ".osl": # compile .osl file ok, oso_path = osl_compile(script_path, report) oso_file_remove = True if ok: # copy .oso from temporary path to .osl directory dst_path = script_path_noext + ".oso" try: shutil.copy2(oso_path, dst_path) except: report({'ERROR'}, "Failed to write .oso file next to external .osl file at " + dst_path) elif os.path.dirname(node.filepath) == "": # module in search path oso_path = node.filepath oso_file_remove = False ok = True else: # unknown report({'ERROR'}, "External shader script must have .osl or .oso extension, or be a module name") ok = False if ok: node.bytecode = "" node.bytecode_hash = "" elif node.mode == 'INTERNAL' and node.script: # internal script, we will store bytecode in the node script = node.script osl_path = bpy.path.abspath(script.filepath, library=script.library) if script.is_in_memory or script.is_dirty or script.is_modified or not os.path.exists(osl_path): # write text datablock contents to temporary file osl_file = tempfile.NamedTemporaryFile(mode='w', suffix=".osl", delete=False) osl_file.write(script.as_string()) osl_file.close() ok, oso_path = osl_compile(osl_file.name, report) oso_file_remove = False os.remove(osl_file.name) else: # compile text datablock from disk directly ok, oso_path = osl_compile(osl_path, report) oso_file_remove = False if ok: # read bytecode try: oso = open(oso_path, 'r') node.bytecode = oso.read() oso.close() except: import traceback traceback.print_exc() report({'ERROR'}, "Can't read OSO bytecode to store in node at %r" % oso_path) ok = False
# now update node with new sockets ok = _cycles.osl_update_node(node.id_data.as_pointer(), node.as_pointer(), oso_path) if not ok: report({'ERROR'}, "OSL query failed to open " + oso_path) else: report({'ERROR'}, "OSL script compilation failed, see console for errors") # remove temporary oso file if oso_file_remove: try: os.remove(oso_path) except: pass return ok
else: report({'WARNING'}, "No text or file specified in node, nothing to compile") return if ok:
random_line_split
vivado.py
def check_vivado(args): vivado_path = get_command("vivado") if vivado_path == None: # Look for the default Vivado install directory if os.name == 'nt': base_dir = r"C:\Xilinx\Vivado" else:
if os.path.exists(base_dir): for file in os.listdir(base_dir): bin_dir = base_dir + os.path.sep + file + os.path.sep + "bin" if os.path.exists(bin_dir + os.path.sep + "vivado"): os.environ["PATH"] += os.pathsep + bin_dir vivado_path = bin_dir break if vivado_path == None: return (False, "toolchain not found in your PATH", "download it from https://www.xilinx.com/support/download.html") return (True, "found at {}".format(vivado_path))
base_dir = "/opt/Xilinx/Vivado"
conditional_block
vivado.py
def check_vivado(args):
vivado_path = get_command("vivado") if vivado_path == None: # Look for the default Vivado install directory if os.name == 'nt': base_dir = r"C:\Xilinx\Vivado" else: base_dir = "/opt/Xilinx/Vivado" if os.path.exists(base_dir): for file in os.listdir(base_dir): bin_dir = base_dir + os.path.sep + file + os.path.sep + "bin" if os.path.exists(bin_dir + os.path.sep + "vivado"): os.environ["PATH"] += os.pathsep + bin_dir vivado_path = bin_dir break if vivado_path == None: return (False, "toolchain not found in your PATH", "download it from https://www.xilinx.com/support/download.html") return (True, "found at {}".format(vivado_path))
identifier_body
vivado.py
def
(args): vivado_path = get_command("vivado") if vivado_path == None: # Look for the default Vivado install directory if os.name == 'nt': base_dir = r"C:\Xilinx\Vivado" else: base_dir = "/opt/Xilinx/Vivado" if os.path.exists(base_dir): for file in os.listdir(base_dir): bin_dir = base_dir + os.path.sep + file + os.path.sep + "bin" if os.path.exists(bin_dir + os.path.sep + "vivado"): os.environ["PATH"] += os.pathsep + bin_dir vivado_path = bin_dir break if vivado_path == None: return (False, "toolchain not found in your PATH", "download it from https://www.xilinx.com/support/download.html") return (True, "found at {}".format(vivado_path))
check_vivado
identifier_name
vivado.py
def check_vivado(args): vivado_path = get_command("vivado") if vivado_path == None: # Look for the default Vivado install directory if os.name == 'nt': base_dir = r"C:\Xilinx\Vivado" else: base_dir = "/opt/Xilinx/Vivado" if os.path.exists(base_dir):
break if vivado_path == None: return (False, "toolchain not found in your PATH", "download it from https://www.xilinx.com/support/download.html") return (True, "found at {}".format(vivado_path))
for file in os.listdir(base_dir): bin_dir = base_dir + os.path.sep + file + os.path.sep + "bin" if os.path.exists(bin_dir + os.path.sep + "vivado"): os.environ["PATH"] += os.pathsep + bin_dir vivado_path = bin_dir
random_line_split
bottomTabsConfig.tsx
import { OwnerType, TappedTabBarArgs } from "@artsy/cohesion" import { BottomTabType } from "./BottomTabType" export type BottomTabRoute = "/" | "/search" | "/inbox" | "/sales" | "/my-profile" export const BottomTabRoutes = ["/", "/search", "/inbox", "/sales", "/my-profile"] export const bottomTabsConfig: { [k in BottomTabType]: { route: BottomTabRoute analyticsDescription: TappedTabBarArgs["tab"] } } = { home: { route: "/", analyticsDescription: OwnerType.home, }, search: { route: "/search", analyticsDescription: OwnerType.search, },
route: "/inbox", analyticsDescription: OwnerType.inbox, }, sell: { route: "/sales", analyticsDescription: OwnerType.sell, }, profile: { route: "/my-profile", analyticsDescription: OwnerType.profile, }, }
inbox: {
random_line_split
Icon.tsx
import * as React from 'react' import Base from '../../libs/Base' import './Icon.less' const colors = ['normal', 'gray', 'blue', 'red', 'orange', 'green'] export interface IIconProps { name?: string, spinning?: boolean, fit?: boolean, clickable?: boolean, color?: 'normal' | 'gray' | 'blue' | 'red' | 'orange' | 'green' | string onClick?: React.MouseEventHandler<any> } export default class Icon extends Base<IIconProps> { render ()
}
{ const {name, children, color: _color = 'normal', onClick} = this.props const colorClass = colors.indexOf(_color) > -1 ? `whc-icon--${_color}` : '' const colorStyle = !colorClass && _color ? {color: _color} : undefined const fit = this.props.fit ? ' fa-fw' : '' const spin = this.props.spinning ? ' fa-spin' : '' const clickable = !!onClick || this.props.clickable return ( name || children ? ( <span {...this.rootProps(['whc-icon', colorClass, {clickable}], colorStyle)} onClick={onClick}> {name && <i className={`fa fa-${name}${spin}${fit}`}/>} {children !== undefined && <span className='whc-icon__text'>{children}</span>} </span> ) : null ) }
identifier_body
Icon.tsx
import * as React from 'react' import Base from '../../libs/Base' import './Icon.less' const colors = ['normal', 'gray', 'blue', 'red', 'orange', 'green'] export interface IIconProps { name?: string, spinning?: boolean, fit?: boolean, clickable?: boolean, color?: 'normal' | 'gray' | 'blue' | 'red' | 'orange' | 'green' | string onClick?: React.MouseEventHandler<any> } export default class
extends Base<IIconProps> { render () { const {name, children, color: _color = 'normal', onClick} = this.props const colorClass = colors.indexOf(_color) > -1 ? `whc-icon--${_color}` : '' const colorStyle = !colorClass && _color ? {color: _color} : undefined const fit = this.props.fit ? ' fa-fw' : '' const spin = this.props.spinning ? ' fa-spin' : '' const clickable = !!onClick || this.props.clickable return ( name || children ? ( <span {...this.rootProps(['whc-icon', colorClass, {clickable}], colorStyle)} onClick={onClick}> {name && <i className={`fa fa-${name}${spin}${fit}`}/>} {children !== undefined && <span className='whc-icon__text'>{children}</span>} </span> ) : null ) } }
Icon
identifier_name
Icon.tsx
import * as React from 'react' import Base from '../../libs/Base' import './Icon.less' const colors = ['normal', 'gray', 'blue', 'red', 'orange', 'green'] export interface IIconProps { name?: string, spinning?: boolean, fit?: boolean, clickable?: boolean, color?: 'normal' | 'gray' | 'blue' | 'red' | 'orange' | 'green' | string
render () { const {name, children, color: _color = 'normal', onClick} = this.props const colorClass = colors.indexOf(_color) > -1 ? `whc-icon--${_color}` : '' const colorStyle = !colorClass && _color ? {color: _color} : undefined const fit = this.props.fit ? ' fa-fw' : '' const spin = this.props.spinning ? ' fa-spin' : '' const clickable = !!onClick || this.props.clickable return ( name || children ? ( <span {...this.rootProps(['whc-icon', colorClass, {clickable}], colorStyle)} onClick={onClick}> {name && <i className={`fa fa-${name}${spin}${fit}`}/>} {children !== undefined && <span className='whc-icon__text'>{children}</span>} </span> ) : null ) } }
onClick?: React.MouseEventHandler<any> } export default class Icon extends Base<IIconProps> {
random_line_split
Rule.ts
import { SchemaType, Rule as IRule, RuleClass, CustomValidator, RuleSpecConstraint, FieldRules, ValidationContext, RuleSpec, ValidationMarker, RuleTypeConstraint, Validator, Block, } from '@sanity/types' import {cloneDeep, get} from 'lodash' import ValidationErrorClass from './ValidationError' import escapeRegex from './util/escapeRegex' import convertToValidationMarker from './util/convertToValidationMarker' import pathToString from './util/pathToString' import genericValidator from './validators/genericValidator' import booleanValidator from './validators/booleanValidator' import numberValidator from './validators/numberValidator' import stringValidator from './validators/stringValidator' import arrayValidator from './validators/arrayValidator' import objectValidator from './validators/objectValidator' import dateValidator from './validators/dateValidator' const typeValidators = { Boolean: booleanValidator, Number: numberValidator, String: stringValidator, Array: arrayValidator, Object: objectValidator, Date: dateValidator, } const getBaseType = (type: SchemaType | undefined): SchemaType | undefined => { return type && type.type ? getBaseType(type.type) : type } const isFieldRef = (constraint: unknown): constraint is {type: symbol; path: string | string[]} => { if (typeof constraint !== 'object' || !constraint) return false return (constraint as Record<string, unknown>).type === Rule.FIELD_REF } const EMPTY_ARRAY: unknown[] = [] const FIELD_REF = Symbol('FIELD_REF') const ruleConstraintTypes: RuleTypeConstraint[] = [ 'Array', 'Boolean', 'Date', 'Number', 'Object', 'String', ] // Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types` // setup. Classes are a bit weird in the `@sanity/types` package because classes // create an actual javascript class while simultaneously creating a type // definition. // // This implicitly creates two types: // 1. the instance type — `Rule` and // 2. the static/class type - `RuleClass` // // The `RuleClass` type contains the static methods and the `Rule` instance // contains the instance methods. // // This package exports the RuleClass as a value without implicitly exporting // an instance definition. This should help reminder downstream users to import // from the `@sanity/types` package. const Rule: RuleClass = class Rule implements IRule { static readonly FIELD_REF = FIELD_REF static array = (def?: SchemaType): Rule => new Rule(def).type('Array') static object = (def?: SchemaType): Rule => new Rule(def).type('Object') static string = (def?: SchemaType): Rule => new Rule(def).type('String') static number = (def?: SchemaType): Rule => new Rule(def).type('Number') static boolean = (def?: SchemaType): Rule => new Rule(def).type('Boolean') static dateTime = (def?: SchemaType): Rule => new Rule(def).type('Date') static valueOfField = (path: string | string[]): {type: symbol; path: string | string[]} => ({ type: FIELD_REF, path, }) _type: RuleTypeConstraint | undefined = undefined _level: 'error' | 'warning' | 'info' | undefined = undefined _required: 'required' | 'optional' | undefined = undefined _typeDef: SchemaType | undefined = undefined _message: string | undefined = undefined _rules: RuleSpec[] = [] _fieldRules: FieldRules | undefined = undefined constructor(typeDef?: SchemaType) { this._typeDef = typeDef this.reset() } private _mergeRequired(next: Rule) { if (this._required === 'required' || next._required === 'required') return 'required' if (this._required === 'optional' || next._required === 'optional') return 'optional' return undefined } // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class valueOfField = Rule.valueOfField.bind(Rule) error(message?: string): Rule { const rule = this.clone() rule._level = 'error' rule._message = message || undefined return rule } warning(message?: string): Rule { const rule = this.clone() rule._level = 'warning' rule._message = message || undefined return rule } info(message?: string): Rule { const rule = this.clone() rule._level = 'info' rule._message = message || undefined return rule } reset(): this { this._type = this._type || undefined this._rules = (this._rules || []).filter((rule) => rule.flag === 'type') this._message = undefined this._required = undefined this._level = 'error' this._fieldRules = undefined return this } isRequired(): boolean { return this._required === 'required' } clone(): Rule { const rule = new Rule() rule._type = this._type rule._message = this._message rule._required = this._required rule._rules = cloneDeep(this._rules) rule._level = this._level rule._fieldRules = this._fieldRules rule._typeDef = this._typeDef return rule } cloneWithRules(rules: RuleSpec[]): Rule { const rule = this.clone() const newRules = new Set() rules.forEach((curr) => { if (curr.flag === 'type') { rule._type = curr.constraint } newRules.add(curr.flag) }) rule._rules = rule._rules .filter((curr) => { const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag) const isDuplicate = newRules.has(curr.flag) return !(disallowDuplicate && isDuplicate) }) .concat(rules) return rule } merge(rule: Rule): Rule { if (this._type && rule._type && this._type !== rule._type) { throw new Error('merge() failed: conflicting types') } const newRule = this.cloneWithRules(rule._rules) newRule._type = this._type || rule._type newRule._message = this._message || rule._message newRule._required = this._mergeRequired(rule) newRule._level = this._level === 'error' ? rule._level : this._level return newRule } // Validation flag setters type(targetType: RuleTypeConstraint | Lowercase<RuleTypeConstraint>): Rule { const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}` as Capitalize< typeof targetType > if (!ruleConstraintTypes.includes(type)) { throw new Error(`Unknown type "${targetType}"`) } const rule = this.cloneWithRules([{flag: 'type', constraint: type}]) rule._type = type return rule } all(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'all', constraint: children}]) } either(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'either', constraint: children}]) } // Shared rules optional(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'optional'}]) rule._required = 'optional' return rule } required(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'required'}]) rule._required = 'required' return rule } custom<T = unknown>(fn: CustomValidator<T>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } /** * @deprecated use `Rule.custom` instead */ block(fn: CustomValidator<Block>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } min(len: number): Rule { return this.cloneWithRules([{flag: 'min', constraint: len}]) } max(len: number): Rule { return this.cloneWithRules([{flag: 'max', constraint: len}]) } length(len: number): Rule { return this.cloneWithRules([{flag: 'length', constraint: len}]) } valid(value: unknown | unknown[]): Rule { const values = Array.isArray(value) ? value : [value] return this.cloneWithRules([{flag: 'valid', constraint: values}]) } // Numbers only integer(): Rule { return this.cloneWithRules([{flag: 'integer'}]) } precision(limit: number): Rule { return this.cloneWithRules([{flag: 'precision', constraint: limit}]) } positive(): Rule { return this.cloneWithRules([{flag: 'min', constraint: 0}]) } negative(): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: 0}]) } greaterThan(num: number): Rule { return this.cloneWithRules([{flag: 'greaterThan', constraint: num}]) } lessThan(num: number): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: num}]) } // String only uppercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'uppercase'}]) } lowercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'lowercase'}]) } regex(pattern: RegExp, name: string, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, name: string): Rule regex(pattern: RegExp): Rule regex( pattern: RegExp, a?: string | {name?: string; invert?: boolean}, b?: {name?: string; invert?: boolean} ): Rule { const name = typeof a === 'string' ? a : a?.name ?? b?.name const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert const constraint: RuleSpecConstraint<'regex'> = { pattern, name, invert: invert || false, } return this.cloneWithRules([{flag: 'regex', constraint}]) } email(): Rule { return this.cloneWithRules([{flag: 'email'}]) } uri(opts?: { scheme?: (string | RegExp) | Array<string | RegExp> allowRelative?: boolean relativeOnly?: boolean allowCredentials?: boolean }): Rule { const optsScheme = opts?.scheme || ['http', 'https'] const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme] if (!schemes.length) {
const constraint: RuleSpecConstraint<'uri'> = { options: { scheme: schemes.map((scheme) => { if (!(scheme instanceof RegExp) && typeof scheme !== 'string') { throw new Error('scheme must be a RegExp or a String') } return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme }), allowRelative: opts?.allowRelative || false, relativeOnly: opts?.relativeOnly || false, allowCredentials: opts?.allowCredentials || false, }, } return this.cloneWithRules([{flag: 'uri', constraint}]) } // Array only unique(): Rule { return this.cloneWithRules([{flag: 'unique'}]) } // Objects only reference(): Rule { return this.cloneWithRules([{flag: 'reference'}]) } fields(rules: FieldRules): Rule { if (this._type !== 'Object') { throw new Error('fields() can only be called on an object type') } const rule = this.cloneWithRules([]) rule._fieldRules = rules return rule } assetRequired(): Rule { const base = getBaseType(this._typeDef) let assetType: 'Asset' | 'Image' | 'File' if (base && ['image', 'file'].includes(base.name)) { assetType = base.name === 'image' ? 'Image' : 'File' } else { assetType = 'Asset' } return this.cloneWithRules([{flag: 'assetRequired', constraint: {assetType}}]) } async validate(value: unknown, context: ValidationContext = {}): Promise<ValidationMarker[]> { const valueIsEmpty = value === null || value === undefined // Short-circuit on optional, empty fields if (valueIsEmpty && this._required === 'optional') { return EMPTY_ARRAY as ValidationMarker[] } const rules = // Run only the _custom_ functions if the rule is not set to required or optional this._required === undefined && valueIsEmpty ? this._rules.filter((curr) => curr.flag === 'custom') : this._rules const validators = (this._type && typeValidators[this._type]) || genericValidator const results = await Promise.all( rules.map(async (curr) => { if (curr.flag === undefined) { throw new Error('Invalid rule, did not contain "flag"-property') } const validator: Validator | undefined = validators[curr.flag] if (!validator) { const forType = this._type ? `type "${this._type}"` : 'rule without declared type' throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`) } let specConstraint = 'constraint' in curr ? curr.constraint : null if (isFieldRef(specConstraint)) { specConstraint = get(context.parent, specConstraint.path) } let result try { result = await validator(specConstraint, value, this._message, context) } catch (err) { const errorFromException = new ValidationErrorClass( `${pathToString(context.path)}: Exception occurred while validating value: ${ err.message }` ) return convertToValidationMarker(errorFromException, 'error', context) } return convertToValidationMarker(result, this._level, context) }) ) return results.flat() } } export default Rule
throw new Error('scheme must have at least 1 scheme specified') }
conditional_block
Rule.ts
import { SchemaType, Rule as IRule, RuleClass, CustomValidator, RuleSpecConstraint, FieldRules, ValidationContext, RuleSpec, ValidationMarker, RuleTypeConstraint, Validator, Block, } from '@sanity/types' import {cloneDeep, get} from 'lodash' import ValidationErrorClass from './ValidationError' import escapeRegex from './util/escapeRegex' import convertToValidationMarker from './util/convertToValidationMarker' import pathToString from './util/pathToString' import genericValidator from './validators/genericValidator' import booleanValidator from './validators/booleanValidator' import numberValidator from './validators/numberValidator' import stringValidator from './validators/stringValidator' import arrayValidator from './validators/arrayValidator' import objectValidator from './validators/objectValidator' import dateValidator from './validators/dateValidator' const typeValidators = { Boolean: booleanValidator, Number: numberValidator, String: stringValidator, Array: arrayValidator, Object: objectValidator, Date: dateValidator, } const getBaseType = (type: SchemaType | undefined): SchemaType | undefined => { return type && type.type ? getBaseType(type.type) : type } const isFieldRef = (constraint: unknown): constraint is {type: symbol; path: string | string[]} => { if (typeof constraint !== 'object' || !constraint) return false return (constraint as Record<string, unknown>).type === Rule.FIELD_REF } const EMPTY_ARRAY: unknown[] = [] const FIELD_REF = Symbol('FIELD_REF') const ruleConstraintTypes: RuleTypeConstraint[] = [ 'Array', 'Boolean', 'Date', 'Number', 'Object', 'String', ] // Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types` // setup. Classes are a bit weird in the `@sanity/types` package because classes // create an actual javascript class while simultaneously creating a type // definition. // // This implicitly creates two types: // 1. the instance type — `Rule` and // 2. the static/class type - `RuleClass` // // The `RuleClass` type contains the static methods and the `Rule` instance // contains the instance methods. // // This package exports the RuleClass as a value without implicitly exporting // an instance definition. This should help reminder downstream users to import // from the `@sanity/types` package. const Rule: RuleClass = class Rule implements IRule { static readonly FIELD_REF = FIELD_REF static array = (def?: SchemaType): Rule => new Rule(def).type('Array') static object = (def?: SchemaType): Rule => new Rule(def).type('Object') static string = (def?: SchemaType): Rule => new Rule(def).type('String') static number = (def?: SchemaType): Rule => new Rule(def).type('Number') static boolean = (def?: SchemaType): Rule => new Rule(def).type('Boolean') static dateTime = (def?: SchemaType): Rule => new Rule(def).type('Date') static valueOfField = (path: string | string[]): {type: symbol; path: string | string[]} => ({ type: FIELD_REF, path, }) _type: RuleTypeConstraint | undefined = undefined _level: 'error' | 'warning' | 'info' | undefined = undefined _required: 'required' | 'optional' | undefined = undefined _typeDef: SchemaType | undefined = undefined _message: string | undefined = undefined _rules: RuleSpec[] = [] _fieldRules: FieldRules | undefined = undefined constructor(typeDef?: SchemaType) { this._typeDef = typeDef this.reset() } private _mergeRequired(next: Rule) { if (this._required === 'required' || next._required === 'required') return 'required' if (this._required === 'optional' || next._required === 'optional') return 'optional' return undefined } // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class valueOfField = Rule.valueOfField.bind(Rule) error(message?: string): Rule { const rule = this.clone() rule._level = 'error' rule._message = message || undefined return rule } warning(message?: string): Rule { const rule = this.clone() rule._level = 'warning' rule._message = message || undefined return rule } info(message?: string): Rule { const rule = this.clone() rule._level = 'info' rule._message = message || undefined return rule } reset(): this { this._type = this._type || undefined this._rules = (this._rules || []).filter((rule) => rule.flag === 'type') this._message = undefined this._required = undefined this._level = 'error' this._fieldRules = undefined return this } isRequired(): boolean { return this._required === 'required' } clone(): Rule { const rule = new Rule() rule._type = this._type rule._message = this._message rule._required = this._required rule._rules = cloneDeep(this._rules) rule._level = this._level rule._fieldRules = this._fieldRules rule._typeDef = this._typeDef return rule } cloneWithRules(rules: RuleSpec[]): Rule { const rule = this.clone() const newRules = new Set() rules.forEach((curr) => { if (curr.flag === 'type') { rule._type = curr.constraint } newRules.add(curr.flag) }) rule._rules = rule._rules .filter((curr) => { const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag) const isDuplicate = newRules.has(curr.flag) return !(disallowDuplicate && isDuplicate) }) .concat(rules) return rule } merge(rule: Rule): Rule { if (this._type && rule._type && this._type !== rule._type) { throw new Error('merge() failed: conflicting types') } const newRule = this.cloneWithRules(rule._rules) newRule._type = this._type || rule._type newRule._message = this._message || rule._message newRule._required = this._mergeRequired(rule) newRule._level = this._level === 'error' ? rule._level : this._level return newRule } // Validation flag setters type(targetType: RuleTypeConstraint | Lowercase<RuleTypeConstraint>): Rule { const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}` as Capitalize< typeof targetType > if (!ruleConstraintTypes.includes(type)) { throw new Error(`Unknown type "${targetType}"`) } const rule = this.cloneWithRules([{flag: 'type', constraint: type}]) rule._type = type return rule } all(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'all', constraint: children}]) } either(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'either', constraint: children}]) } // Shared rules optional(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'optional'}]) rule._required = 'optional' return rule } required(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'required'}]) rule._required = 'required' return rule } custom<T = unknown>(fn: CustomValidator<T>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } /** * @deprecated use `Rule.custom` instead */ block(fn: CustomValidator<Block>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } min(len: number): Rule { return this.cloneWithRules([{flag: 'min', constraint: len}]) } max(len: number): Rule { return this.cloneWithRules([{flag: 'max', constraint: len}]) } length(len: number): Rule { return this.cloneWithRules([{flag: 'length', constraint: len}]) } valid(value: unknown | unknown[]): Rule { const values = Array.isArray(value) ? value : [value] return this.cloneWithRules([{flag: 'valid', constraint: values}]) } // Numbers only integer(): Rule { return this.cloneWithRules([{flag: 'integer'}]) } precision(limit: number): Rule { return this.cloneWithRules([{flag: 'precision', constraint: limit}]) } positive(): Rule { return this.cloneWithRules([{flag: 'min', constraint: 0}]) } negative(): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: 0}]) } greaterThan(num: number): Rule { return this.cloneWithRules([{flag: 'greaterThan', constraint: num}]) } lessThan(num: number): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: num}]) } // String only uppercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'uppercase'}]) } lowercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'lowercase'}]) } regex(pattern: RegExp, name: string, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, name: string): Rule regex(pattern: RegExp): Rule re
pattern: RegExp, a?: string | {name?: string; invert?: boolean}, b?: {name?: string; invert?: boolean} ): Rule { const name = typeof a === 'string' ? a : a?.name ?? b?.name const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert const constraint: RuleSpecConstraint<'regex'> = { pattern, name, invert: invert || false, } return this.cloneWithRules([{flag: 'regex', constraint}]) } email(): Rule { return this.cloneWithRules([{flag: 'email'}]) } uri(opts?: { scheme?: (string | RegExp) | Array<string | RegExp> allowRelative?: boolean relativeOnly?: boolean allowCredentials?: boolean }): Rule { const optsScheme = opts?.scheme || ['http', 'https'] const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme] if (!schemes.length) { throw new Error('scheme must have at least 1 scheme specified') } const constraint: RuleSpecConstraint<'uri'> = { options: { scheme: schemes.map((scheme) => { if (!(scheme instanceof RegExp) && typeof scheme !== 'string') { throw new Error('scheme must be a RegExp or a String') } return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme }), allowRelative: opts?.allowRelative || false, relativeOnly: opts?.relativeOnly || false, allowCredentials: opts?.allowCredentials || false, }, } return this.cloneWithRules([{flag: 'uri', constraint}]) } // Array only unique(): Rule { return this.cloneWithRules([{flag: 'unique'}]) } // Objects only reference(): Rule { return this.cloneWithRules([{flag: 'reference'}]) } fields(rules: FieldRules): Rule { if (this._type !== 'Object') { throw new Error('fields() can only be called on an object type') } const rule = this.cloneWithRules([]) rule._fieldRules = rules return rule } assetRequired(): Rule { const base = getBaseType(this._typeDef) let assetType: 'Asset' | 'Image' | 'File' if (base && ['image', 'file'].includes(base.name)) { assetType = base.name === 'image' ? 'Image' : 'File' } else { assetType = 'Asset' } return this.cloneWithRules([{flag: 'assetRequired', constraint: {assetType}}]) } async validate(value: unknown, context: ValidationContext = {}): Promise<ValidationMarker[]> { const valueIsEmpty = value === null || value === undefined // Short-circuit on optional, empty fields if (valueIsEmpty && this._required === 'optional') { return EMPTY_ARRAY as ValidationMarker[] } const rules = // Run only the _custom_ functions if the rule is not set to required or optional this._required === undefined && valueIsEmpty ? this._rules.filter((curr) => curr.flag === 'custom') : this._rules const validators = (this._type && typeValidators[this._type]) || genericValidator const results = await Promise.all( rules.map(async (curr) => { if (curr.flag === undefined) { throw new Error('Invalid rule, did not contain "flag"-property') } const validator: Validator | undefined = validators[curr.flag] if (!validator) { const forType = this._type ? `type "${this._type}"` : 'rule without declared type' throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`) } let specConstraint = 'constraint' in curr ? curr.constraint : null if (isFieldRef(specConstraint)) { specConstraint = get(context.parent, specConstraint.path) } let result try { result = await validator(specConstraint, value, this._message, context) } catch (err) { const errorFromException = new ValidationErrorClass( `${pathToString(context.path)}: Exception occurred while validating value: ${ err.message }` ) return convertToValidationMarker(errorFromException, 'error', context) } return convertToValidationMarker(result, this._level, context) }) ) return results.flat() } } export default Rule
gex(
identifier_name
Rule.ts
import { SchemaType, Rule as IRule, RuleClass, CustomValidator, RuleSpecConstraint, FieldRules, ValidationContext, RuleSpec, ValidationMarker, RuleTypeConstraint, Validator, Block, } from '@sanity/types' import {cloneDeep, get} from 'lodash' import ValidationErrorClass from './ValidationError' import escapeRegex from './util/escapeRegex' import convertToValidationMarker from './util/convertToValidationMarker' import pathToString from './util/pathToString' import genericValidator from './validators/genericValidator' import booleanValidator from './validators/booleanValidator' import numberValidator from './validators/numberValidator' import stringValidator from './validators/stringValidator' import arrayValidator from './validators/arrayValidator' import objectValidator from './validators/objectValidator' import dateValidator from './validators/dateValidator' const typeValidators = { Boolean: booleanValidator, Number: numberValidator, String: stringValidator, Array: arrayValidator, Object: objectValidator, Date: dateValidator, } const getBaseType = (type: SchemaType | undefined): SchemaType | undefined => { return type && type.type ? getBaseType(type.type) : type } const isFieldRef = (constraint: unknown): constraint is {type: symbol; path: string | string[]} => { if (typeof constraint !== 'object' || !constraint) return false return (constraint as Record<string, unknown>).type === Rule.FIELD_REF } const EMPTY_ARRAY: unknown[] = [] const FIELD_REF = Symbol('FIELD_REF') const ruleConstraintTypes: RuleTypeConstraint[] = [ 'Array', 'Boolean', 'Date', 'Number', 'Object', 'String', ] // Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types` // setup. Classes are a bit weird in the `@sanity/types` package because classes // create an actual javascript class while simultaneously creating a type // definition. // // This implicitly creates two types: // 1. the instance type — `Rule` and // 2. the static/class type - `RuleClass` // // The `RuleClass` type contains the static methods and the `Rule` instance // contains the instance methods. // // This package exports the RuleClass as a value without implicitly exporting // an instance definition. This should help reminder downstream users to import // from the `@sanity/types` package. const Rule: RuleClass = class Rule implements IRule { static readonly FIELD_REF = FIELD_REF static array = (def?: SchemaType): Rule => new Rule(def).type('Array') static object = (def?: SchemaType): Rule => new Rule(def).type('Object') static string = (def?: SchemaType): Rule => new Rule(def).type('String') static number = (def?: SchemaType): Rule => new Rule(def).type('Number') static boolean = (def?: SchemaType): Rule => new Rule(def).type('Boolean') static dateTime = (def?: SchemaType): Rule => new Rule(def).type('Date') static valueOfField = (path: string | string[]): {type: symbol; path: string | string[]} => ({ type: FIELD_REF, path, }) _type: RuleTypeConstraint | undefined = undefined _level: 'error' | 'warning' | 'info' | undefined = undefined _required: 'required' | 'optional' | undefined = undefined _typeDef: SchemaType | undefined = undefined _message: string | undefined = undefined _rules: RuleSpec[] = [] _fieldRules: FieldRules | undefined = undefined constructor(typeDef?: SchemaType) { this._typeDef = typeDef this.reset() } private _mergeRequired(next: Rule) { if (this._required === 'required' || next._required === 'required') return 'required' if (this._required === 'optional' || next._required === 'optional') return 'optional' return undefined } // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class valueOfField = Rule.valueOfField.bind(Rule) error(message?: string): Rule { const rule = this.clone() rule._level = 'error' rule._message = message || undefined return rule } warning(message?: string): Rule { const rule = this.clone() rule._level = 'warning' rule._message = message || undefined return rule } info(message?: string): Rule { const rule = this.clone() rule._level = 'info' rule._message = message || undefined return rule } reset(): this { this._type = this._type || undefined this._rules = (this._rules || []).filter((rule) => rule.flag === 'type') this._message = undefined this._required = undefined this._level = 'error' this._fieldRules = undefined return this } isRequired(): boolean { return this._required === 'required' } clone(): Rule { const rule = new Rule() rule._type = this._type rule._message = this._message rule._required = this._required rule._rules = cloneDeep(this._rules) rule._level = this._level rule._fieldRules = this._fieldRules rule._typeDef = this._typeDef return rule } cloneWithRules(rules: RuleSpec[]): Rule { const rule = this.clone() const newRules = new Set() rules.forEach((curr) => { if (curr.flag === 'type') { rule._type = curr.constraint } newRules.add(curr.flag) }) rule._rules = rule._rules .filter((curr) => { const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag) const isDuplicate = newRules.has(curr.flag) return !(disallowDuplicate && isDuplicate) }) .concat(rules) return rule } merge(rule: Rule): Rule { if (this._type && rule._type && this._type !== rule._type) { throw new Error('merge() failed: conflicting types') } const newRule = this.cloneWithRules(rule._rules) newRule._type = this._type || rule._type newRule._message = this._message || rule._message newRule._required = this._mergeRequired(rule) newRule._level = this._level === 'error' ? rule._level : this._level return newRule } // Validation flag setters type(targetType: RuleTypeConstraint | Lowercase<RuleTypeConstraint>): Rule { const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}` as Capitalize< typeof targetType > if (!ruleConstraintTypes.includes(type)) { throw new Error(`Unknown type "${targetType}"`) } const rule = this.cloneWithRules([{flag: 'type', constraint: type}]) rule._type = type return rule } all(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'all', constraint: children}]) } either(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'either', constraint: children}]) } // Shared rules optional(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'optional'}]) rule._required = 'optional' return rule } required(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'required'}]) rule._required = 'required' return rule } custom<T = unknown>(fn: CustomValidator<T>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } /** * @deprecated use `Rule.custom` instead */ block(fn: CustomValidator<Block>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } min(len: number): Rule { return this.cloneWithRules([{flag: 'min', constraint: len}]) } max(len: number): Rule { return this.cloneWithRules([{flag: 'max', constraint: len}]) } length(len: number): Rule { return this.cloneWithRules([{flag: 'length', constraint: len}]) } valid(value: unknown | unknown[]): Rule { const values = Array.isArray(value) ? value : [value] return this.cloneWithRules([{flag: 'valid', constraint: values}]) } // Numbers only integer(): Rule { return this.cloneWithRules([{flag: 'integer'}]) } precision(limit: number): Rule { return this.cloneWithRules([{flag: 'precision', constraint: limit}]) } positive(): Rule { return this.cloneWithRules([{flag: 'min', constraint: 0}]) } negative(): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: 0}]) } greaterThan(num: number): Rule { return this.cloneWithRules([{flag: 'greaterThan', constraint: num}]) } lessThan(num: number): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: num}]) } // String only uppercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'uppercase'}]) } lowercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'lowercase'}]) } regex(pattern: RegExp, name: string, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, name: string): Rule regex(pattern: RegExp): Rule regex( pattern: RegExp, a?: string | {name?: string; invert?: boolean}, b?: {name?: string; invert?: boolean} ): Rule { const name = typeof a === 'string' ? a : a?.name ?? b?.name const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert const constraint: RuleSpecConstraint<'regex'> = { pattern, name, invert: invert || false, } return this.cloneWithRules([{flag: 'regex', constraint}]) } email(): Rule { return this.cloneWithRules([{flag: 'email'}]) } uri(opts?: { scheme?: (string | RegExp) | Array<string | RegExp> allowRelative?: boolean relativeOnly?: boolean allowCredentials?: boolean
throw new Error('scheme must have at least 1 scheme specified') } const constraint: RuleSpecConstraint<'uri'> = { options: { scheme: schemes.map((scheme) => { if (!(scheme instanceof RegExp) && typeof scheme !== 'string') { throw new Error('scheme must be a RegExp or a String') } return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme }), allowRelative: opts?.allowRelative || false, relativeOnly: opts?.relativeOnly || false, allowCredentials: opts?.allowCredentials || false, }, } return this.cloneWithRules([{flag: 'uri', constraint}]) } // Array only unique(): Rule { return this.cloneWithRules([{flag: 'unique'}]) } // Objects only reference(): Rule { return this.cloneWithRules([{flag: 'reference'}]) } fields(rules: FieldRules): Rule { if (this._type !== 'Object') { throw new Error('fields() can only be called on an object type') } const rule = this.cloneWithRules([]) rule._fieldRules = rules return rule } assetRequired(): Rule { const base = getBaseType(this._typeDef) let assetType: 'Asset' | 'Image' | 'File' if (base && ['image', 'file'].includes(base.name)) { assetType = base.name === 'image' ? 'Image' : 'File' } else { assetType = 'Asset' } return this.cloneWithRules([{flag: 'assetRequired', constraint: {assetType}}]) } async validate(value: unknown, context: ValidationContext = {}): Promise<ValidationMarker[]> { const valueIsEmpty = value === null || value === undefined // Short-circuit on optional, empty fields if (valueIsEmpty && this._required === 'optional') { return EMPTY_ARRAY as ValidationMarker[] } const rules = // Run only the _custom_ functions if the rule is not set to required or optional this._required === undefined && valueIsEmpty ? this._rules.filter((curr) => curr.flag === 'custom') : this._rules const validators = (this._type && typeValidators[this._type]) || genericValidator const results = await Promise.all( rules.map(async (curr) => { if (curr.flag === undefined) { throw new Error('Invalid rule, did not contain "flag"-property') } const validator: Validator | undefined = validators[curr.flag] if (!validator) { const forType = this._type ? `type "${this._type}"` : 'rule without declared type' throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`) } let specConstraint = 'constraint' in curr ? curr.constraint : null if (isFieldRef(specConstraint)) { specConstraint = get(context.parent, specConstraint.path) } let result try { result = await validator(specConstraint, value, this._message, context) } catch (err) { const errorFromException = new ValidationErrorClass( `${pathToString(context.path)}: Exception occurred while validating value: ${ err.message }` ) return convertToValidationMarker(errorFromException, 'error', context) } return convertToValidationMarker(result, this._level, context) }) ) return results.flat() } } export default Rule
}): Rule { const optsScheme = opts?.scheme || ['http', 'https'] const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme] if (!schemes.length) {
random_line_split
Rule.ts
import { SchemaType, Rule as IRule, RuleClass, CustomValidator, RuleSpecConstraint, FieldRules, ValidationContext, RuleSpec, ValidationMarker, RuleTypeConstraint, Validator, Block, } from '@sanity/types' import {cloneDeep, get} from 'lodash' import ValidationErrorClass from './ValidationError' import escapeRegex from './util/escapeRegex' import convertToValidationMarker from './util/convertToValidationMarker' import pathToString from './util/pathToString' import genericValidator from './validators/genericValidator' import booleanValidator from './validators/booleanValidator' import numberValidator from './validators/numberValidator' import stringValidator from './validators/stringValidator' import arrayValidator from './validators/arrayValidator' import objectValidator from './validators/objectValidator' import dateValidator from './validators/dateValidator' const typeValidators = { Boolean: booleanValidator, Number: numberValidator, String: stringValidator, Array: arrayValidator, Object: objectValidator, Date: dateValidator, } const getBaseType = (type: SchemaType | undefined): SchemaType | undefined => { return type && type.type ? getBaseType(type.type) : type } const isFieldRef = (constraint: unknown): constraint is {type: symbol; path: string | string[]} => { if (typeof constraint !== 'object' || !constraint) return false return (constraint as Record<string, unknown>).type === Rule.FIELD_REF } const EMPTY_ARRAY: unknown[] = [] const FIELD_REF = Symbol('FIELD_REF') const ruleConstraintTypes: RuleTypeConstraint[] = [ 'Array', 'Boolean', 'Date', 'Number', 'Object', 'String', ] // Note: `RuleClass` and `Rule` are split to fit the current `@sanity/types` // setup. Classes are a bit weird in the `@sanity/types` package because classes // create an actual javascript class while simultaneously creating a type // definition. // // This implicitly creates two types: // 1. the instance type — `Rule` and // 2. the static/class type - `RuleClass` // // The `RuleClass` type contains the static methods and the `Rule` instance // contains the instance methods. // // This package exports the RuleClass as a value without implicitly exporting // an instance definition. This should help reminder downstream users to import // from the `@sanity/types` package. const Rule: RuleClass = class Rule implements IRule { static readonly FIELD_REF = FIELD_REF static array = (def?: SchemaType): Rule => new Rule(def).type('Array') static object = (def?: SchemaType): Rule => new Rule(def).type('Object') static string = (def?: SchemaType): Rule => new Rule(def).type('String') static number = (def?: SchemaType): Rule => new Rule(def).type('Number') static boolean = (def?: SchemaType): Rule => new Rule(def).type('Boolean') static dateTime = (def?: SchemaType): Rule => new Rule(def).type('Date') static valueOfField = (path: string | string[]): {type: symbol; path: string | string[]} => ({ type: FIELD_REF, path, }) _type: RuleTypeConstraint | undefined = undefined _level: 'error' | 'warning' | 'info' | undefined = undefined _required: 'required' | 'optional' | undefined = undefined _typeDef: SchemaType | undefined = undefined _message: string | undefined = undefined _rules: RuleSpec[] = [] _fieldRules: FieldRules | undefined = undefined constructor(typeDef?: SchemaType) { this._typeDef = typeDef this.reset() } private _mergeRequired(next: Rule) { if (this._required === 'required' || next._required === 'required') return 'required' if (this._required === 'optional' || next._required === 'optional') return 'optional' return undefined } // Alias to static method, since we often have access to an _instance_ of a rule but not the actual Rule class valueOfField = Rule.valueOfField.bind(Rule) error(message?: string): Rule { const rule = this.clone() rule._level = 'error' rule._message = message || undefined return rule } warning(message?: string): Rule { const rule = this.clone() rule._level = 'warning' rule._message = message || undefined return rule } info(message?: string): Rule { const rule = this.clone() rule._level = 'info' rule._message = message || undefined return rule } reset(): this { this._type = this._type || undefined this._rules = (this._rules || []).filter((rule) => rule.flag === 'type') this._message = undefined this._required = undefined this._level = 'error' this._fieldRules = undefined return this } isRequired(): boolean { return this._required === 'required' } clone(): Rule { const rule = new Rule() rule._type = this._type rule._message = this._message rule._required = this._required rule._rules = cloneDeep(this._rules) rule._level = this._level rule._fieldRules = this._fieldRules rule._typeDef = this._typeDef return rule } cloneWithRules(rules: RuleSpec[]): Rule { const rule = this.clone() const newRules = new Set() rules.forEach((curr) => { if (curr.flag === 'type') { rule._type = curr.constraint } newRules.add(curr.flag) }) rule._rules = rule._rules .filter((curr) => { const disallowDuplicate = ['type', 'uri', 'email'].includes(curr.flag) const isDuplicate = newRules.has(curr.flag) return !(disallowDuplicate && isDuplicate) }) .concat(rules) return rule } merge(rule: Rule): Rule { if (this._type && rule._type && this._type !== rule._type) { throw new Error('merge() failed: conflicting types') } const newRule = this.cloneWithRules(rule._rules) newRule._type = this._type || rule._type newRule._message = this._message || rule._message newRule._required = this._mergeRequired(rule) newRule._level = this._level === 'error' ? rule._level : this._level return newRule } // Validation flag setters type(targetType: RuleTypeConstraint | Lowercase<RuleTypeConstraint>): Rule {
all(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'all', constraint: children}]) } either(children: Rule[]): Rule { return this.cloneWithRules([{flag: 'either', constraint: children}]) } // Shared rules optional(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'optional'}]) rule._required = 'optional' return rule } required(): Rule { const rule = this.cloneWithRules([{flag: 'presence', constraint: 'required'}]) rule._required = 'required' return rule } custom<T = unknown>(fn: CustomValidator<T>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } /** * @deprecated use `Rule.custom` instead */ block(fn: CustomValidator<Block>): Rule { return this.cloneWithRules([{flag: 'custom', constraint: fn as CustomValidator}]) } min(len: number): Rule { return this.cloneWithRules([{flag: 'min', constraint: len}]) } max(len: number): Rule { return this.cloneWithRules([{flag: 'max', constraint: len}]) } length(len: number): Rule { return this.cloneWithRules([{flag: 'length', constraint: len}]) } valid(value: unknown | unknown[]): Rule { const values = Array.isArray(value) ? value : [value] return this.cloneWithRules([{flag: 'valid', constraint: values}]) } // Numbers only integer(): Rule { return this.cloneWithRules([{flag: 'integer'}]) } precision(limit: number): Rule { return this.cloneWithRules([{flag: 'precision', constraint: limit}]) } positive(): Rule { return this.cloneWithRules([{flag: 'min', constraint: 0}]) } negative(): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: 0}]) } greaterThan(num: number): Rule { return this.cloneWithRules([{flag: 'greaterThan', constraint: num}]) } lessThan(num: number): Rule { return this.cloneWithRules([{flag: 'lessThan', constraint: num}]) } // String only uppercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'uppercase'}]) } lowercase(): Rule { return this.cloneWithRules([{flag: 'stringCasing', constraint: 'lowercase'}]) } regex(pattern: RegExp, name: string, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, options: {name?: string; invert?: boolean}): Rule regex(pattern: RegExp, name: string): Rule regex(pattern: RegExp): Rule regex( pattern: RegExp, a?: string | {name?: string; invert?: boolean}, b?: {name?: string; invert?: boolean} ): Rule { const name = typeof a === 'string' ? a : a?.name ?? b?.name const invert = typeof a === 'string' ? false : a?.invert ?? b?.invert const constraint: RuleSpecConstraint<'regex'> = { pattern, name, invert: invert || false, } return this.cloneWithRules([{flag: 'regex', constraint}]) } email(): Rule { return this.cloneWithRules([{flag: 'email'}]) } uri(opts?: { scheme?: (string | RegExp) | Array<string | RegExp> allowRelative?: boolean relativeOnly?: boolean allowCredentials?: boolean }): Rule { const optsScheme = opts?.scheme || ['http', 'https'] const schemes = Array.isArray(optsScheme) ? optsScheme : [optsScheme] if (!schemes.length) { throw new Error('scheme must have at least 1 scheme specified') } const constraint: RuleSpecConstraint<'uri'> = { options: { scheme: schemes.map((scheme) => { if (!(scheme instanceof RegExp) && typeof scheme !== 'string') { throw new Error('scheme must be a RegExp or a String') } return typeof scheme === 'string' ? new RegExp(`^${escapeRegex(scheme)}$`) : scheme }), allowRelative: opts?.allowRelative || false, relativeOnly: opts?.relativeOnly || false, allowCredentials: opts?.allowCredentials || false, }, } return this.cloneWithRules([{flag: 'uri', constraint}]) } // Array only unique(): Rule { return this.cloneWithRules([{flag: 'unique'}]) } // Objects only reference(): Rule { return this.cloneWithRules([{flag: 'reference'}]) } fields(rules: FieldRules): Rule { if (this._type !== 'Object') { throw new Error('fields() can only be called on an object type') } const rule = this.cloneWithRules([]) rule._fieldRules = rules return rule } assetRequired(): Rule { const base = getBaseType(this._typeDef) let assetType: 'Asset' | 'Image' | 'File' if (base && ['image', 'file'].includes(base.name)) { assetType = base.name === 'image' ? 'Image' : 'File' } else { assetType = 'Asset' } return this.cloneWithRules([{flag: 'assetRequired', constraint: {assetType}}]) } async validate(value: unknown, context: ValidationContext = {}): Promise<ValidationMarker[]> { const valueIsEmpty = value === null || value === undefined // Short-circuit on optional, empty fields if (valueIsEmpty && this._required === 'optional') { return EMPTY_ARRAY as ValidationMarker[] } const rules = // Run only the _custom_ functions if the rule is not set to required or optional this._required === undefined && valueIsEmpty ? this._rules.filter((curr) => curr.flag === 'custom') : this._rules const validators = (this._type && typeValidators[this._type]) || genericValidator const results = await Promise.all( rules.map(async (curr) => { if (curr.flag === undefined) { throw new Error('Invalid rule, did not contain "flag"-property') } const validator: Validator | undefined = validators[curr.flag] if (!validator) { const forType = this._type ? `type "${this._type}"` : 'rule without declared type' throw new Error(`Validator for flag "${curr.flag}" not found for ${forType}`) } let specConstraint = 'constraint' in curr ? curr.constraint : null if (isFieldRef(specConstraint)) { specConstraint = get(context.parent, specConstraint.path) } let result try { result = await validator(specConstraint, value, this._message, context) } catch (err) { const errorFromException = new ValidationErrorClass( `${pathToString(context.path)}: Exception occurred while validating value: ${ err.message }` ) return convertToValidationMarker(errorFromException, 'error', context) } return convertToValidationMarker(result, this._level, context) }) ) return results.flat() } } export default Rule
const type = `${targetType.slice(0, 1).toUpperCase()}${targetType.slice(1)}` as Capitalize< typeof targetType > if (!ruleConstraintTypes.includes(type)) { throw new Error(`Unknown type "${targetType}"`) } const rule = this.cloneWithRules([{flag: 'type', constraint: type}]) rule._type = type return rule }
identifier_body
smd.py
import numpy as np import sys from trw_utils import * from heterogenous_crf import inference_gco from pyqpbo import binary_general_graph from scipy.optimize import fmin_l_bfgs_b def trw(node_weights, edges, edge_weights, y, max_iter=100, verbose=0, tol=1e-3, get_energy=None): n_nodes, n_states = node_weights.shape n_edges = edges.shape[0] y_hat = [] lambdas = np.zeros(n_nodes) mu = np.zeros((n_nodes, n_states)) learning_rate = 0.1 energy_history = [] primal_history = [] pairwise = [] for k in xrange(n_states): y_hat.append(np.zeros(n_states)) _pairwise = np.zeros((n_edges, 2, 2)) for i in xrange(n_edges): _pairwise[i,1,0] = _pairwise[i,0,1] = -0.5 * edge_weights[i,k,k] pairwise.append(_pairwise) for i in xrange(n_edges): e1, e2 = edges[i] node_weights[e1,:] += 0.5 * np.diag(edge_weights[i,:,:]) node_weights[e2,:] += 0.5 * np.diag(edge_weights[i,:,:]) for iteration in xrange(max_iter): dmu = np.zeros((n_nodes, n_states)) unaries = node_weights + mu x, f_val, d = fmin_l_bfgs_b(f, np.zeros(n_nodes), args=(unaries, pairwise, edges), maxiter=50, pgtol=1e-5) E = np.sum(x) for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = unaries[:,k] + x y_hat[k], energy = binary_general_graph(edges, new_unaries, pairwise[k]) E -= 0.5*energy dmu[:,k] -= y_hat[k] y_hat_kappa, energy = optimize_kappa(y, mu, 1, n_nodes, n_states) E += energy dmu[np.ogrid[:dmu.shape[0]], y_hat_kappa] += 1 mu -= learning_rate * dmu energy_history.append(E) lambda_sum = np.zeros((n_nodes, n_states)) for k in xrange(n_states): lambda_sum[:,k] = y_hat[k] lambda_sum = lambda_sum / np.sum(lambda_sum, axis=1, keepdims=True) if get_energy is not None: primal = get_energy(get_labelling(lambda_sum)) primal_history.append(primal) else: primal = 0 if iteration: learning_rate = 1. / np.sqrt(iteration) if verbose: print 'Iteration {}: energy={}, primal={}'.format(iteration, E, primal) if iteration > 0 and np.abs(E - energy_history[-2]) < tol: if verbose: print 'Converged' break info = {'primal': primal_history, 'dual': energy_history, 'iteration': iteration} return lambda_sum, y_hat_kappa, info def
(x, node_weights, pairwise, edges): n_nodes, n_states = node_weights.shape dual = 0 dlambda = np.zeros(n_nodes) for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = node_weights[:,k] + x y_hat, energy = binary_general_graph(edges, new_unaries, pairwise[k]) dual += 0.5 * energy dlambda += y_hat dlambda -= 1 dual -= np.sum(x) #print dual return -dual, -dlambda
f
identifier_name
smd.py
import numpy as np import sys from trw_utils import * from heterogenous_crf import inference_gco from pyqpbo import binary_general_graph from scipy.optimize import fmin_l_bfgs_b def trw(node_weights, edges, edge_weights, y, max_iter=100, verbose=0, tol=1e-3, get_energy=None): n_nodes, n_states = node_weights.shape n_edges = edges.shape[0] y_hat = [] lambdas = np.zeros(n_nodes) mu = np.zeros((n_nodes, n_states)) learning_rate = 0.1 energy_history = [] primal_history = [] pairwise = [] for k in xrange(n_states): y_hat.append(np.zeros(n_states)) _pairwise = np.zeros((n_edges, 2, 2)) for i in xrange(n_edges): _pairwise[i,1,0] = _pairwise[i,0,1] = -0.5 * edge_weights[i,k,k] pairwise.append(_pairwise) for i in xrange(n_edges):
for iteration in xrange(max_iter): dmu = np.zeros((n_nodes, n_states)) unaries = node_weights + mu x, f_val, d = fmin_l_bfgs_b(f, np.zeros(n_nodes), args=(unaries, pairwise, edges), maxiter=50, pgtol=1e-5) E = np.sum(x) for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = unaries[:,k] + x y_hat[k], energy = binary_general_graph(edges, new_unaries, pairwise[k]) E -= 0.5*energy dmu[:,k] -= y_hat[k] y_hat_kappa, energy = optimize_kappa(y, mu, 1, n_nodes, n_states) E += energy dmu[np.ogrid[:dmu.shape[0]], y_hat_kappa] += 1 mu -= learning_rate * dmu energy_history.append(E) lambda_sum = np.zeros((n_nodes, n_states)) for k in xrange(n_states): lambda_sum[:,k] = y_hat[k] lambda_sum = lambda_sum / np.sum(lambda_sum, axis=1, keepdims=True) if get_energy is not None: primal = get_energy(get_labelling(lambda_sum)) primal_history.append(primal) else: primal = 0 if iteration: learning_rate = 1. / np.sqrt(iteration) if verbose: print 'Iteration {}: energy={}, primal={}'.format(iteration, E, primal) if iteration > 0 and np.abs(E - energy_history[-2]) < tol: if verbose: print 'Converged' break info = {'primal': primal_history, 'dual': energy_history, 'iteration': iteration} return lambda_sum, y_hat_kappa, info def f(x, node_weights, pairwise, edges): n_nodes, n_states = node_weights.shape dual = 0 dlambda = np.zeros(n_nodes) for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = node_weights[:,k] + x y_hat, energy = binary_general_graph(edges, new_unaries, pairwise[k]) dual += 0.5 * energy dlambda += y_hat dlambda -= 1 dual -= np.sum(x) #print dual return -dual, -dlambda
e1, e2 = edges[i] node_weights[e1,:] += 0.5 * np.diag(edge_weights[i,:,:]) node_weights[e2,:] += 0.5 * np.diag(edge_weights[i,:,:])
conditional_block
smd.py
import numpy as np import sys from trw_utils import * from heterogenous_crf import inference_gco from pyqpbo import binary_general_graph from scipy.optimize import fmin_l_bfgs_b def trw(node_weights, edges, edge_weights, y, max_iter=100, verbose=0, tol=1e-3, get_energy=None):
def f(x, node_weights, pairwise, edges): n_nodes, n_states = node_weights.shape dual = 0 dlambda = np.zeros(n_nodes) for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = node_weights[:,k] + x y_hat, energy = binary_general_graph(edges, new_unaries, pairwise[k]) dual += 0.5 * energy dlambda += y_hat dlambda -= 1 dual -= np.sum(x) #print dual return -dual, -dlambda
n_nodes, n_states = node_weights.shape n_edges = edges.shape[0] y_hat = [] lambdas = np.zeros(n_nodes) mu = np.zeros((n_nodes, n_states)) learning_rate = 0.1 energy_history = [] primal_history = [] pairwise = [] for k in xrange(n_states): y_hat.append(np.zeros(n_states)) _pairwise = np.zeros((n_edges, 2, 2)) for i in xrange(n_edges): _pairwise[i,1,0] = _pairwise[i,0,1] = -0.5 * edge_weights[i,k,k] pairwise.append(_pairwise) for i in xrange(n_edges): e1, e2 = edges[i] node_weights[e1,:] += 0.5 * np.diag(edge_weights[i,:,:]) node_weights[e2,:] += 0.5 * np.diag(edge_weights[i,:,:]) for iteration in xrange(max_iter): dmu = np.zeros((n_nodes, n_states)) unaries = node_weights + mu x, f_val, d = fmin_l_bfgs_b(f, np.zeros(n_nodes), args=(unaries, pairwise, edges), maxiter=50, pgtol=1e-5) E = np.sum(x) for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = unaries[:,k] + x y_hat[k], energy = binary_general_graph(edges, new_unaries, pairwise[k]) E -= 0.5*energy dmu[:,k] -= y_hat[k] y_hat_kappa, energy = optimize_kappa(y, mu, 1, n_nodes, n_states) E += energy dmu[np.ogrid[:dmu.shape[0]], y_hat_kappa] += 1 mu -= learning_rate * dmu energy_history.append(E) lambda_sum = np.zeros((n_nodes, n_states)) for k in xrange(n_states): lambda_sum[:,k] = y_hat[k] lambda_sum = lambda_sum / np.sum(lambda_sum, axis=1, keepdims=True) if get_energy is not None: primal = get_energy(get_labelling(lambda_sum)) primal_history.append(primal) else: primal = 0 if iteration: learning_rate = 1. / np.sqrt(iteration) if verbose: print 'Iteration {}: energy={}, primal={}'.format(iteration, E, primal) if iteration > 0 and np.abs(E - energy_history[-2]) < tol: if verbose: print 'Converged' break info = {'primal': primal_history, 'dual': energy_history, 'iteration': iteration} return lambda_sum, y_hat_kappa, info
identifier_body
smd.py
import numpy as np import sys from trw_utils import * from heterogenous_crf import inference_gco from pyqpbo import binary_general_graph from scipy.optimize import fmin_l_bfgs_b def trw(node_weights, edges, edge_weights, y, max_iter=100, verbose=0, tol=1e-3, get_energy=None): n_nodes, n_states = node_weights.shape n_edges = edges.shape[0] y_hat = [] lambdas = np.zeros(n_nodes) mu = np.zeros((n_nodes, n_states)) learning_rate = 0.1 energy_history = [] primal_history = [] pairwise = [] for k in xrange(n_states): y_hat.append(np.zeros(n_states)) _pairwise = np.zeros((n_edges, 2, 2)) for i in xrange(n_edges): _pairwise[i,1,0] = _pairwise[i,0,1] = -0.5 * edge_weights[i,k,k] pairwise.append(_pairwise) for i in xrange(n_edges): e1, e2 = edges[i] node_weights[e1,:] += 0.5 * np.diag(edge_weights[i,:,:]) node_weights[e2,:] += 0.5 * np.diag(edge_weights[i,:,:]) for iteration in xrange(max_iter): dmu = np.zeros((n_nodes, n_states)) unaries = node_weights + mu x, f_val, d = fmin_l_bfgs_b(f, np.zeros(n_nodes), args=(unaries, pairwise, edges), maxiter=50, pgtol=1e-5) E = np.sum(x) for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = unaries[:,k] + x y_hat[k], energy = binary_general_graph(edges, new_unaries, pairwise[k]) E -= 0.5*energy dmu[:,k] -= y_hat[k] y_hat_kappa, energy = optimize_kappa(y, mu, 1, n_nodes, n_states) E += energy dmu[np.ogrid[:dmu.shape[0]], y_hat_kappa] += 1 mu -= learning_rate * dmu energy_history.append(E) lambda_sum = np.zeros((n_nodes, n_states)) for k in xrange(n_states): lambda_sum[:,k] = y_hat[k] lambda_sum = lambda_sum / np.sum(lambda_sum, axis=1, keepdims=True) if get_energy is not None: primal = get_energy(get_labelling(lambda_sum)) primal_history.append(primal) else: primal = 0 if iteration: learning_rate = 1. / np.sqrt(iteration) if verbose: print 'Iteration {}: energy={}, primal={}'.format(iteration, E, primal) if iteration > 0 and np.abs(E - energy_history[-2]) < tol: if verbose: print 'Converged' break info = {'primal': primal_history, 'dual': energy_history, 'iteration': iteration} return lambda_sum, y_hat_kappa, info def f(x, node_weights, pairwise, edges): n_nodes, n_states = node_weights.shape dual = 0
for k in xrange(n_states): new_unaries = np.zeros((n_nodes, 2)) new_unaries[:,1] = node_weights[:,k] + x y_hat, energy = binary_general_graph(edges, new_unaries, pairwise[k]) dual += 0.5 * energy dlambda += y_hat dlambda -= 1 dual -= np.sum(x) #print dual return -dual, -dlambda
dlambda = np.zeros(n_nodes)
random_line_split
associated-types-no-suitable-supertrait.rs
// Check that we get an error when you use `<Self as Get>::Value` in // the trait definition but `Self` does not, in fact, implement `Get`. // // See also associated-types-no-suitable-supertrait-2.rs, which checks // that we see the same error if we get around to checking the default // method body. // // See also run-pass/associated-types-projection-to-unrelated-trait.rs, // which checks that the trait interface itself is not considered an // error as long as all impls satisfy the constraint. trait Get { type Value; } trait Other { fn
<U:Get>(&self, foo: U, bar: <Self as Get>::Value) {} //~^ ERROR the trait bound `Self: Get` is not satisfied } impl<T:Get> Other for T { fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value) {} //~^ ERROR the trait bound `(T, U): Get` is not satisfied } fn main() { }
uhoh
identifier_name
associated-types-no-suitable-supertrait.rs
// Check that we get an error when you use `<Self as Get>::Value` in // the trait definition but `Self` does not, in fact, implement `Get`. // // See also associated-types-no-suitable-supertrait-2.rs, which checks // that we see the same error if we get around to checking the default // method body. // // See also run-pass/associated-types-projection-to-unrelated-trait.rs, // which checks that the trait interface itself is not considered an // error as long as all impls satisfy the constraint. trait Get { type Value; } trait Other { fn uhoh<U:Get>(&self, foo: U, bar: <Self as Get>::Value) {} //~^ ERROR the trait bound `Self: Get` is not satisfied } impl<T:Get> Other for T { fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value)
//~^ ERROR the trait bound `(T, U): Get` is not satisfied } fn main() { }
{}
identifier_body
associated-types-no-suitable-supertrait.rs
// Check that we get an error when you use `<Self as Get>::Value` in // the trait definition but `Self` does not, in fact, implement `Get`. // // See also associated-types-no-suitable-supertrait-2.rs, which checks // that we see the same error if we get around to checking the default // method body.
trait Get { type Value; } trait Other { fn uhoh<U:Get>(&self, foo: U, bar: <Self as Get>::Value) {} //~^ ERROR the trait bound `Self: Get` is not satisfied } impl<T:Get> Other for T { fn uhoh<U:Get>(&self, foo: U, bar: <(T, U) as Get>::Value) {} //~^ ERROR the trait bound `(T, U): Get` is not satisfied } fn main() { }
// // See also run-pass/associated-types-projection-to-unrelated-trait.rs, // which checks that the trait interface itself is not considered an // error as long as all impls satisfy the constraint.
random_line_split
package.js
Package.describe({ name: 'ndemoreau:azimulti-views-bootstrap', summary: 'Azimuth Multilanguage CMS frontend templates (using Bootstrap 3.x)', version: '0.4.3', git: 'https://github.com/ndemoreau/azimulti-views-bootstrap' }); Package.on_use(function (api) { api.use(['less@1.0.11', 'templating@1.0.9', 'mizzao:bootstrap-3@3.3.0'], 'client'); api.use('ndemoreau:azimulti-core@0.4.3', {unordered: true}); api.add_files('css/style.less', 'client'); api.add_files('blocks/block/block.html', 'client'); api.add_files('blocks/block_with_title/block_with_title.html', 'client'); api.add_files('blocks/block_multi/block_multi.html', 'client'); api.add_files('blocks/block_multi_with_title/block_multi_with_title.html', 'client');
api.add_files('pages/home_page/home_page.html', 'client'); api.add_files('pages/page_default/page_default.html', 'client'); api.add_files('pages/sidebar_left/sidebar_left.html', 'client'); api.add_files('pages/sidebar_left_fixed/sidebar_left_fixed.html', 'client'); api.add_files('pages/sidebar_right/sidebar_right.html', 'client'); api.add_files('views/404.html', 'client'); api.add_files('views/block_display.html', 'client'); api.add_files('views/footer.html', 'client'); api.add_files('views/header.html', 'client'); api.add_files('views/layout.html', 'client'); api.add_files('views/not_authorized.html', 'client'); api.add_files('views/accounts/account_buttons.html', 'client'); api.add_files('views/accounts/error.html', 'client'); api.add_files('views/accounts/forgot_password.html', 'client'); api.add_files('views/accounts/login.html', 'client'); api.add_files('views/accounts/sign_up.html', 'client'); api.add_files('views/accounts/social.html', 'client'); api.add_files('lib/utils.js', 'client'); });
random_line_split
exceptions.js
import { ListWrapper } from 'angular2/src/facade/collection'; import { stringify, isBlank } from 'angular2/src/facade/lang'; import { BaseException, WrappedException } from 'angular2/src/facade/exceptions'; function findFirstClosedCycle(keys) { var res = []; for (var i = 0; i < keys.length; ++i) { if (ListWrapper.contains(res, keys[i])) { res.push(keys[i]); return res; } else { res.push(keys[i]); } } return res; } function constructResolvingPath(keys) { if (keys.length > 1) { var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var tokenStrs = reversed.map(k => stringify(k.token)); return " (" + tokenStrs.join(' -> ') + ")"; } else { return ""; } } /** * Base class for all errors arising from misconfigured providers. */ export class AbstractProviderError extends BaseException { constructor(injector, key, constructResolvingMessage) { super("DI Exception"); this.keys = [key]; this.injectors = [injector]; this.constructResolvingMessage = constructResolvingMessage; this.message = this.constructResolvingMessage(this.keys); } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); this.message = this.constructResolvingMessage(this.keys); } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the * {@link Injector} does not have a {@link Provider} for {@link Key}. * * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview)) * * ```typescript * class A { * constructor(b:B) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` */ export class NoProviderError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { var first = stringify(ListWrapper.first(keys).token); return `No provider for ${first}!${constructResolvingPath(keys)}`; }); } } /** * Thrown when dependencies form a cycle. * * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info)) * * ```typescript * var injector = Injector.resolveAndCreate([ * provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}), * provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]}) * ]); * * expect(() => injector.get("one")).toThrowError(); * ``` * * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed. */ export class CyclicDependencyError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`; }); } } /** * Thrown when a constructing type returns with an Error. * * The `InstantiationError` class contains the original error plus the dependency graph which caused * this object to be instantiated. * * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview)) * * ```typescript * class A { * constructor() { * throw new Error('message'); * } * } * * var injector = Injector.resolveAndCreate([A]); * try { * injector.get(A); * } catch (e) { * expect(e instanceof InstantiationError).toBe(true); * expect(e.originalException.message).toEqual("message"); * expect(e.originalStack).toBeDefined(); * } * ``` */ export class InstantiationError extends WrappedException { constructor(injector, originalException, originalStack, key) { super("DI Exception", originalException, originalStack, null); this.keys = [key]; this.injectors = [injector]; } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); } get wrapperMessage() { var first = stringify(ListWrapper.first(this.keys).token); return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`; } get causeKey() { return this.keys[0]; } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector} * creation. * * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview)) * * ```typescript * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError(); * ``` */ export class InvalidProviderError extends BaseException { constructor(provider) { super("Invalid provider - only instances of Provider and Type are allowed, got: " + provider.toString()); } } /** * Thrown when the class has no annotation information. * * Lack of annotation information prevents the {@link Injector} from determining which dependencies * need to be injected into the constructor. * * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview)) * * ```typescript * class A { * constructor(b) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` * * This error is also thrown when the class not marked with {@link Injectable} has parameter types. * * ```typescript * class B {} * * class A { * constructor(b:B) {} // no information about the parameter types of A is available at runtime. * } * * expect(() => Injector.resolveAndCreate([A,B])).toThrowError(); * ``` */ export class NoAnnotationError extends BaseException { constructor(typeOrFunc, params) { super(NoAnnotationError._genMessage(typeOrFunc, params)); } static _genMessage(typeOrFunc, params) { var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; if (isBlank(parameter) || parameter.length == 0) { signature.push('?'); } else { signature.push(parameter.map(stringify).join(' ')); } } return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; } } /** * Thrown when getting an object by index. * * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview)) * * ```typescript * class A {} * * var injector = Injector.resolveAndCreate([A]); * * expect(() => injector.getAt(100)).toThrowError(); * ``` */ export class OutOfBoundsError extends BaseException {
(index) { super(`Index ${index} is out-of-bounds.`); } } // TODO: add a working example after alpha38 is released /** * Thrown when a multi provider and a regular provider are bound to the same token. * * ### Example * * ```typescript * expect(() => Injector.resolveAndCreate([ * new Provider("Strings", {useValue: "string1", multi: true}), * new Provider("Strings", {useValue: "string2", multi: false}) * ])).toThrowError(); * ``` */ export class MixingMultiProvidersWithRegularProvidersError extends BaseException { constructor(provider1, provider2) { super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + provider2.toString()); } } //# sourceMappingURL=exceptions.js.map
constructor
identifier_name