Return a "traceback" of Sass imports.
965684
def format_sass_stack(self):
        """"""
        if not self.rule_stack:
            return ""

        ret = ["on ", self.format_file_and_line(self.rule_stack[0]), "\n"]
        last_file = self.rule_stack[0].source_file

        # TODO this could go away if rules knew their import chains...
        # TODO this doesn't mention mixins or function calls.  really need to
        # track the call stack better.  atm we skip other calls in the same
        # file because most of them are just nesting, but they might not be!
        # TODO the line number is wrong here for @imports, because we don't
        # have access to the UnparsedBlock representing the import!
        # TODO @content is completely broken; it's basically textual inclusion
        for rule in self.rule_stack[1:]:
            if rule.source_file is not last_file:
                ret.extend((
                    "imported from ", self.format_file_and_line(rule), "\n"))
            last_file = rule.source_file

        return "".join(ret)
24043
def module_is_imported(modname, scope=None):
    """"""
    # return early if modname is not even cached
    if not module_is_in_cache(modname):
        return False

    if scope is None:  # use globals() of the caller by default
        scope = inspect.stack()[1][0].f_globals

    for m in scope.values():
        if isinstance(m, type(sys)) and m.__name__ == modname:
            return True

    return False
1341656
def clean_traceback(tb):
    ''''''
    prefix = __file__[:__file__.find("feat/common/error.py")]
    regex = re.compile("(\s*File\s*\")(%s)([a-zA-Z-_\. \\/]*)(\".*)"
                       % prefix.replace("\\", "\\\\"))

    def cleanup(line):
        m = regex.match(line)
        if m:
            return m.group(1) + ".../" + m.group(3) + m.group(4)
        else:
            return line

    return '\n'.join(map(cleanup, tb.split('\n')))
1359711
function compileSass(path, ext, file, callback) {
  let compiledCss = sass.renderSync({
    file: path,
    outputStyle: 'compressed',
  });
  callback(null, compiledCss.css);
}
126882
function sassCompile() {
    gulp.src(sassSrcFiles)
    .pipe(sourcemaps.init())
    .pipe(sass(sassOptions).on('error', sass.logError))
    .pipe(autoprefixer(autoprefixerOptions))
    .pipe(sourcemaps.write('./maps'))
    .pipe(gulp.dest('./dist/crudl-ui/css'))
}
284362
def parse_traceback(msg, site_path="site-packages", in_app_prefix="c7n"):
    

    data = {}
    lines = list(filter(None, msg.split('\n')))
    data['frames'] = []
    err_ctx = None

    for l in lines[1:-1]:
        l = l.strip() # noqa E741
        if l.startswith('Traceback'):
            continue
        elif l.startswith('File'):
            abs_path, lineno, function = l.split(',', 3)
            abs_path = abs_path[abs_path.find('"'):-1]
            f_path = abs_path[abs_path.find(site_path) + len(site_path) + 1:]
            module = f_path[:f_path.find('.')].replace('/', '.').strip('.')
            lineno = int(lineno.strip().split()[1])
            function = function.strip().split()[-1]
            err_ctx = dict(lineno=lineno,
                           abs_path=abs_path,
                           function=function,
                           filename=f_path,
                           module=module)
            if module.startswith(in_app_prefix):
                err_ctx['in_app'] = True
        elif err_ctx is not None:
            err_ctx['context_line'] = l
            data['frames'].append(err_ctx)
            err_ctx = None

    return lines[0], {
        'type': lines[-1].strip().split(':')[0],
        'value': lines[-1].strip().split(':', 1)[1].strip(),
        'module': data['frames'][-1]['module'],
        'stacktrace': data}
1212171
def _short_traceback(skip=3):
  """"""
  counter, res = 0, []
  # Skipping 3 lines by default: the top (useless) and self-call.
  lines = traceback.format_exc().splitlines()[skip:]
  for l in lines:
    res.append(_shorten_file_path(l))
    if counter % 2 == 1:
      res.append('')
    counter += 1
    # If we see a LayerError, the traceback has already been processed.
    if l.startswith('LayerError'):
      # Skip 4 back except last as these are internal base-layer calls.
      res = res[:-4] + [res[-1]]
      res += lines[counter:]
      break
  return '\n'.join(res)
687555
function sassLoader(content) {
  const callback = this.async();
  const isSync = typeof callback !== 'function';
  const self = this;
  const { resourcePath } = this;

  function addNormalizedDependency(file) {
    // node-sass returns POSIX paths
    self.dependency(path.normalize(file));
  }

  if (isSync) {
    throw new Error(
      'Synchronous compilation is not supported anymore. See https://github.com/webpack-contrib/sass-loader/issues/333'
    );
  }

  let resolve = pify(this.resolve);

  // Supported since v4.27.0
  if (this.getResolve) {
    resolve = this.getResolve({
      mainFields: ['sass', 'main'],
      extensions: ['.scss', '.sass', '.css'],
    });
  }

  const options = normalizeOptions(
    this,
    content,
    webpackImporter(resourcePath, resolve, addNormalizedDependency)
  );

  // Skip empty files, otherwise it will stop webpack, see issue #21
  if (options.data.trim() === '') {
    callback(null, '');
    return;
  }

  const render = getRenderFuncFromSassImpl(
    // eslint-disable-next-line import/no-extraneous-dependencies, global-require
    options.implementation || getDefaultSassImpl()
  );

  render(options, (err, result) => {
    if (err) {
      formatSassError(err, this.resourcePath);

      if (err.file) {
        this.dependency(err.file);
      }

      callback(err);
      return;
    }

    if (result.map && result.map !== '{}') {
      // eslint-disable-next-line no-param-reassign
      result.map = JSON.parse(result.map);
      // result.map.file is an optional property that provides the output filename.
      // Since we don't know the final filename in the webpack build chain yet, it makes no sense to have it.
      // eslint-disable-next-line no-param-reassign
      delete result.map.file;
      // One of the sources is 'stdin' according to dart-sass/node-sass because we've used the data input.
      // Now let's override that value with the correct relative path.
      // Since we specified options.sourceMap = path.join(process.cwd(), "/sass.map"); in normalizeOptions,
      // we know that this path is relative to process.cwd(). This is how node-sass works.
      // eslint-disable-next-line no-param-reassign
      const stdinIndex = result.map.sources.findIndex(
        (source) => source.indexOf('stdin') !== -1
      );

      if (stdinIndex !== -1) {
        result.map.sources[stdinIndex] = path.relative(
          process.cwd(),
          resourcePath
        );
      }
      // node-sass returns POSIX paths, that's why we need to transform them back to native paths.
      // This fixes an error on windows where the source-map module cannot resolve the source maps.
      // @see https://github.com/webpack-contrib/sass-loader/issues/366#issuecomment-279460722
      // eslint-disable-next-line no-param-reassign
      result.map.sourceRoot = path.normalize(result.map.sourceRoot);
      // eslint-disable-next-line no-param-reassign
      result.map.sources = result.map.sources.map(path.normalize);
    } else {
      // eslint-disable-next-line no-param-reassign
      result.map = null;
    }

    result.stats.includedFiles.forEach(addNormalizedDependency);

    callback(null, result.css.toString(), result.map);
  });
}
868247
def compile_sass(input_file, output_file):
    
    from .modules import sass

    if not isinstance(input_file, str):
        raise RuntimeError('SASS compiler takes only a single input file.')

    return {
        'dependencies_fn': sass.sass_dependencies,
        'compiler_fn': sass.sass_compile,
        'input': input_file,
        'output': output_file,
        'kwargs': {},
    }
478828
function getRenderFuncFromSassImpl(module) {
  const { info } = module;
  const components = info.split('\t');

  if (components.length < 2) {
    throw new Error(`Unknown Sass implementation "${info}".`);
  }

  const [implementation, version] = components;

  if (!semver.valid(version)) {
    throw new Error(`Invalid Sass version "${version}".`);
  }

  if (implementation === 'dart-sass') {
    if (!semver.satisfies(version, '^1.3.0')) {
      throw new Error(
        `Dart Sass version ${version} is incompatible with ^1.3.0.`
      );
    }

    return module.render.bind(module);
  } else if (implementation === 'node-sass') {
    if (!semver.satisfies(version, '^4.0.0')) {
      throw new Error(
        `Node Sass version ${version} is incompatible with ^4.0.0.`
      );
    }

    // There is an issue with node-sass when async custom importers are used
    // See https://github.com/sass/node-sass/issues/857#issuecomment-93594360
    // We need to use a job queue to make sure that one thread is always available to the UV lib
    if (nodeSassJobQueue === null) {
      const threadPoolSize = Number(process.env.UV_THREADPOOL_SIZE || 4);

      nodeSassJobQueue = async.queue(
        module.render.bind(module),
        threadPoolSize - 1
      );
    }

    return nodeSassJobQueue.push.bind(nodeSassJobQueue);
  }

  throw new Error(`Unknown Sass implementation "${implementation}".`);
}
327807
def render_css(self, fn=None, text=None, margin='', indent='\t'):
        """"""
        fn = fn or os.path.splitext(self.fn)[0]+'.css'
        if not os.path.exists(os.path.dirname(fn)):
            os.makedirs(os.path.dirname(fn))
        curdir = os.path.abspath(os.curdir)
        os.chdir(os.path.dirname(fn))               # needed in order for scss to relative @import
        text = text or self.render_styles()
        if text != '': text = sass.compile(string=text)
        os.chdir(curdir)
        return CSS(fn=fn, text=text)
1124740
def output_traceback(ex):
    """"""
    # Dump full traceback to console.
    output = "".join(traceback.format_exc()).strip()
    for line in output.split('\n'):
        logging.error(line)
    trace_obj = traceback.extract_tb(ex.__traceback__)[-1]
    trace = [basename(trace_obj[0]), trace_obj[1]]
    name = type(ex).__name__
    output = str(ex).replace('\n', ' ')
    msg = "%s in %s on line %s: %s" % (name, trace[0], trace[1], output)
    return (msg, output)
1004703
function processTraceOpts(options, defaults) {
  var opts = {
    // indicate to plugins to output ES modules instead of System.register for Rollup support
    outputESM: true,
    sourceMaps: false,

    // conditional tracing options
    browser: undefined,
    node: undefined,
    production: undefined,
    dev: undefined,
    conditions: {
      '@system-env|default': true,
      '@system-env|~default': false
    },
    inlineConditions: {},
    traceRuntimePlugin: true,

    // package config tracing (used for bundles only)
    tracePackageConfig: false,

    // when set, automatically excludes non-file URLs that don't resolve to canonical names
    // instead of showing the "Unable to calculate canonical name" error
    excludeURLs: true,
    externals: []
  };

  // ensure user environment overrides default environment
  if (typeof options == 'object') {
    if (typeof options.browser == 'boolean' || typeof options.node == 'boolean') {
      // browser true/false -> node is opposite
      if (typeof options.browser == 'boolean' && typeof options.node != 'boolean')
        options.node = !options.browser;
      // node true/false -> browser is opposite
      else if (typeof options.node == 'boolean' && typeof options.browser != 'boolean')
        options.browser = !options.node;
    }

    // development -> dev backwards compat
    if ('development' in options)
      options.dev = options.development;
    if (typeof options.dev == 'boolean' || typeof options.production == 'boolean') {
      if (typeof options.production != 'boolean')
        options.production = !options.dev;
      if (typeof options.dev != 'boolean')
        options.dev = !options.production;
    }
  }

  extend(opts, defaults);
  extend(opts, options);

  // globalDeps are externals
  if (opts.globalDeps)
    opts.externals = opts.externals.concat(Object.keys(opts.globalDeps));

  // conditional tracing defaults
  if (typeof opts.browser == 'boolean') {
    // browser, node   -> browser, ~browser, node, ~node
    // !browser, node  -> ~browser, node
    // browser, !node  -> browser, ~node
    // !browser, !node -> ~browser, ~node
    opts.conditions['@system-env|browser'] = opts.browser;
    opts.conditions['@system-env|~browser'] = opts.browser === true ? opts.node : !opts.browser;
    opts.conditions['@system-env|node'] = opts.node;
    opts.conditions['@system-env|~node'] = opts.node === true ? opts.browser : !opts.node;
  }
  if (typeof opts.production == 'boolean') {
    opts.conditions['@system-env|production'] = opts.production;
    opts.conditions['@system-env|~production'] = opts.dev;
    opts.conditions['@system-env|dev'] = opts.dev;
    opts.conditions['@system-env|~dev'] = opts.production;
  }

  if (typeof opts.inlineConditions == 'object')
    extend(opts.conditions, opts.inlineConditions);
  else if (opts.inlineConditions === true)
    opts.inlineConditions = opts.conditions;
  else
    opts.inlineConditions = {};

  return opts;
}
486101
def debug(trace=True, backtrace=1, other=None, output=sys.stderr):
    """"""
    from pprint import pprint
    import traceback
    def debugdeco(func):
        def tracer(frame, event, arg):
            print>>output, '--- Tracer: %s, %r' % (event, arg)
            traceback.print_stack(frame, 1, output)
            return tracer
        def wrapped(*a, **k):
            print>>output
            print>>output, '--- Calling %s.%s with:' % (
                getattr(func, '__module__', ''),
                func.__name__
            )
            for i in enumerate(a):
                print>>output, '    | %s: %s' % i
            print>>output, '    | ',
            pprint(k, output)
            print>>output, '    From:'
            for i in traceback.format_stack(sys._getframe(1), backtrace):
                print>>output, i,
            if other:
                print>>output, '---      [ %r ]' % (other(func,a,k))
            if trace: sys.settrace(tracer)
            ret = func(*a, **k)
            if trace: sys.settrace(None)
            #~ a = list(a)
            print>>output, '--- %s.%s returned: %r' % (
                getattr(func, '__module__', ''),
                func.__name__,
                #~ ret not in a and ret or "ARG%s"%a.index(ret)
                ret
            )
            return ret
        return wrapped
    return debugdeco
491603
def analyze_traceback(tb, inspection_level=None, limit=None):
    
    info = []
    tb_level = tb
    extracted_tb = traceback.extract_tb(tb, limit=limit)
    for ii, (filepath, line, module, code) in enumerate(extracted_tb):
        func_source, func_lineno = inspect.getsourcelines(tb_level.tb_frame)

        d = {"File": filepath,
             "Error Line Number": line,
             "Module": module,
             "Error Line": code,
             "Module Line Number": func_lineno,
             "Custom Inspection": {},
             "Source Code": ''}
        if inspection_level is None or len(extracted_tb) - ii <= inspection_level:
            # Perform advanced inspection on the last `inspection_level` tracebacks.
            d['Source Code'] = ''.join(func_source)
            d['Local Variables'] = get_local_references(tb_level)
            d['Object Variables'] = get_object_references(tb_level, d['Source Code'])
        tb_level = getattr(tb_level, 'tb_next', None)
        info.append(d)

    return info
296129
def process_result
      require 'sass'

      if !@options[:update] && !@options[:watch] &&
          @args.first && colon_path?(@args.first)
        if @args.size == 1
          @args = split_colon_path(@args.first)
        else
          @fake_update = true
          @options[:update] = true
        end
      end
      load_compass if @options[:compass]
      return interactive if @options[:interactive]
      return watch_or_update if @options[:watch] || @options[:update]
      super

      if @options[:sourcemap] != :none && @options[:output_filename]
        @options[:sourcemap_filename] = Sass::Util.sourcemap_name(@options[:output_filename])
      end

      @options[:for_engine][:filename] = @options[:filename]
      @options[:for_engine][:css_filename] = @options[:output] if @options[:output].is_a?(String)
      @options[:for_engine][:sourcemap_filename] = @options[:sourcemap_filename]
      @options[:for_engine][:sourcemap] = @options[:sourcemap]

      run
    end
718845
def _check_import(module_names):
    """"""
    diagnostics = {}
    for module_name in module_names:
        try:
            __import__(module_name)
            res = 'ok'
        except ImportError as err:
            res = str(err)
        diagnostics[module_name] = res
    return diagnostics