simple skiplist implementation in c

本文详细介绍了跳表的数据结构设计、初始化、删除、添加、查找、释放等核心操作的实现过程,通过实例代码展示跳表的高效性和灵活性。
#ifndef MY_SKIP_LIST
#define MY_SKIP_LIST

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>

typedef int DataType;

#define MAX_LEVEL 8

struct DataNode;


typedef struct NodeLevel
{
    struct DataNode * forward;
    unsigned span;

}NodeLevel,*PNodeLevel;

/**
data node which stores data with DataType
*/
typedef struct DataNode
{
//    int (*compare)(DataType val1,DataType val2);
    DataType value;
    unsigned level_size;
    NodeLevel level[];

}DataNode,*PDataNode;


/**
skip list struct
*/
typedef struct SkipList
{
    unsigned level;
    unsigned size;
    PDataNode header;

}SkipList,*PSkipList;

/**
 *get rand level for data node created
 */
unsigned rand_level();

/**
 *initialize an empty skiplist
 */
PSkipList skiplist_init();

/**
 *destory a skip list 'sl',and free the memory occupied.
 */
void destory_skiplist(PSkipList *sl);

/**
 *make a new skip list node which stores 'val',
 *returns a pointer to the data node newly made
 */
PDataNode make_node(DataType val,unsigned level);

/**
 *delete a data node with data 'val' from skip list 'sl',
 *returns a pointer of DataNode deleted,
 *if DataNode with data 'val' does not exist,return NULL
 *note:memory occupied by 'val' not freed
 */
PDataNode del(PSkipList sl,DataType val);

/**
 *add a data node with data 'val' from skip list 'sl',
 *returns a pointer of DataNode added,
 *note:memory occupied by 'val' not freed
 */
PDataNode add(PSkipList sl,DataType val);

/**
 *find 'val' in skiplist 'sl',if founed,return the pointer of node with value 'val'
 *if not return NULL
 */
PDataNode find(PSkipList sl,DataType val);

/**
 *free the memory occupied by 'node'
 */
void free_node(PDataNode node);

void print_skiplist(PSkipList sl);
void print_level(PSkipList sl, int i);

#endif // MY_SKIP_LIST
#include "skiplist.h"

unsigned rand_level()
{
    int level = 1;
    while(rand()%2 && level <= MAX_LEVEL)
        level++;
    return level;
}

PDataNode make_node(DataType val,unsigned level)
{
    PDataNode node = (PDataNode)malloc(sizeof(DataNode) + sizeof(NodeLevel)*level);
    if(node == NULL)
        return NULL;

    node->value = val;
    node->level_size = level;

    int i = 0;
    for(i=0; i<level; i++)
    {
        node->level[i].forward = NULL;
        node->level[i].span = 0;
    }
    return node;
}

void free_node(PDataNode node)
{
    if(NULL == node)
        return;
    free(node);
}

PSkipList skiplist_init()
{
    PSkipList sl = NULL;
    sl = (PSkipList)malloc(sizeof(SkipList));
    sl->level = 1;
    sl->size = 0;
    PDataNode header = make_node(INT_MIN,MAX_LEVEL);
    if(header == NULL)
    {
        free(sl);
        return NULL;
    }
    sl->header = header;
    return sl;
}
void destory_skiplist(PSkipList *sl)
{
    if(*sl == NULL) return;

    PDataNode pNode = (*sl)->header->level[0].forward;
    PDataNode next = NULL;
    while(pNode)
    {
        next = pNode->level[0].forward;
        free_node(pNode);
        pNode = next;
    }
    pNode = NULL;
    next = NULL;
    free_node((*sl)->header);
    (*sl)->header = NULL;
    free(*sl);
    (*sl) = NULL;
    return;
}

PDataNode del(PSkipList sl,DataType val)
{
    if(sl == NULL) return NULL;
    PDataNode del_node = NULL;
    PNodeLevel update[MAX_LEVEL];
    int i = MAX_LEVEL - 1;
    PDataNode cur,pre;
    pre = sl->header;
    cur = pre;
    while(i >= 0)
    {
        cur = pre->level[i].forward;
        while(cur != NULL && cur->value < val)
        {
            pre = cur;
            cur = cur->level[i].forward;
        }
        if(cur != NULL && cur->value == val)
        {
            del_node = cur;
        }
        update[i] = &(pre->level[i]);
        i--;
    }

    if(del_node == NULL)
        return NULL;

    i = MAX_LEVEL - 1;
    while(i >= 0)
    {
        if(update[i]->forward == NULL)
        {
            i--;
            continue;
        }
        else if(update[i]->forward->value > val)
        {
            update[i]->span--;
            i--;
        }
        else
        {
            update[i]->forward = del_node->level[i].forward;
            if(del_node->level[i].forward == NULL)
                update[i]->span = 0;
            else
                update[i]->span += del_node->level[i].span - 1;
            i--;
        }
    }
    sl->size--;
    return del_node;
}

PDataNode add(PSkipList sl,DataType val)
{
    if(sl == NULL) return NULL;
    unsigned node_level = rand_level();
    PDataNode pNode = make_node(val,node_level);
    printf("Level:%d   value:%d\n",node_level,val);
    if(pNode == NULL) return NULL;

    PNodeLevel update[MAX_LEVEL];
    //查找插入位置的遍历路径上处于第i层的节点在链表中的排位,头节点为rank[MAX_LEVEL-1]=0
    //查找从最高层开始且头节点在链表中是第一个,所以rank[MAX_LEVEL-1]=0
    unsigned rank[MAX_LEVEL] = {0};
    int i =  MAX_LEVEL-1;
    PDataNode cur,pre;
    pre = sl->header;
    cur = pre;
    while(i >= 0)
    {
        rank[i] = (i == MAX_LEVEL-1 ? 0 : rank[i+1]);
        cur = pre->level[i].forward;
        while(cur && cur->value < val)
        {
            rank[i] += pre->level[i].span;
            pre = cur;
            cur = cur->level[i].forward;
        }
        if(cur && cur->value == val)
            return NULL;
        update[i] = &(pre->level[i]);
        i--;
    }
    i = MAX_LEVEL-1;
    for(;i >=0; i--)
    {
        if(update[i]->forward == NULL && i > node_level-1)
        {
            continue;
        }
        else if(update[i]->forward == NULL && i <= node_level-1)
        {
            update[i]->forward = pNode;
            //节点的插入位置一定是在查找路基上第0层节点的后面一个
            //rank[0] - rank[i]得到的是查找路径上要更新的第层节点距离第0层节点的距离跨度,
            //这个跨度+1就得到了更新路劲上第i层节点到插入节点的跨度
            update[i]->span = (rank[0] - rank[i]) + 1;
        }
        else if(update[i]->forward && i > node_level-1)
        {
            update[i]->span++;
        }
        else
        {
            pNode->level[i].forward = update[i]->forward;
            //pNode->level[i].span = (update[i]->span + 1) - ((rank[0] - rank[i]) + 1);
            pNode->level[i].span = update[i]->span - (rank[0] - rank[i]);
            update[i]->forward = pNode;
            update[i]->span = (rank[0] - rank[i]) + 1;
        }
    }
    sl->size++;
    return pNode;
}

PDataNode find(PSkipList sl,DataType val)
{
    if(sl == NULL) return NULL;
    PDataNode pre  = sl->header;
    PDataNode cur = pre;
    int i =  MAX_LEVEL-1;
    unsigned rank[MAX_LEVEL-1] = {0};
    while(i >= 0)
    {
        rank[i] = (i == MAX_LEVEL-1 ? 0 : rank[i+1]);
        cur = pre->level[i].forward;
        while(cur != NULL && cur->value < val)
        {
            rank[i] += pre->level[i].span;
            pre = cur;
            cur = cur->level[i].forward;
        }
        if(cur != NULL && cur->value == val)
        {
            printf("val=%d,rank:%u\n",val,rank[i]+1);
            return cur;
        }
        i--;
    }
    return NULL;
}

void print_level(PSkipList sl, int i)
{
    PDataNode pNode = sl->header;
    printf("level  %d    ",i);
    while(pNode)
    {
        printf("%d",pNode->value);
        int num = pNode->level[i].span;
        while(num > 0)
        {
            printf("-");
            num--;
        }
        pNode = pNode->level[i].forward;
    }
    printf("\n");
}

void print_skiplist(PSkipList sl)
{
    if(sl == NULL)
    {
        printf("Null list");
        return ;
    }
    int i = MAX_LEVEL - 1;
    while(i >= 0)
    {
        print_level(sl,i);
        i--;
    }
}

#include <stdio.h>
#include <stdlib.h>
#include "skiplist.h"
int main()
{
    PSkipList sl = skiplist_init();
    DataType vals[] = {1,3,5,7,9,2,4,6,8,10,11,15,12,18,21,31,56,100,94,68,60,88,66};
    unsigned val_size = sizeof(vals)/sizeof(vals[0]);
    printf("value number = %u\n",val_size);
    unsigned i = 0;
    for(;i < val_size; i++)
    {
        add(sl,vals[i]);
    }
    print_skiplist(sl);
    find(sl,31);
    find(sl,100);
    find(sl,66);

    PDataNode del_node = del(sl,31);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,88);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,21);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,6);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,94);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,60);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,68);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,100);
    free_node(del_node);
    print_skiplist(sl);

    del_node = del(sl,1);
    free_node(del_node);
    print_skiplist(sl);

    del_node = NULL;

    destory_skiplist(&sl);
    print_skiplist(sl);

    return 0;
}


\documentclass[12pt]{article} \usepackage{amsmath, amssymb} \usepackage{graphicx} \usepackage{geometry} \usepackage{setspace} \usepackage{caption} \usepackage{titlesec} % 页面设置 \geometry{a4paper, margin=1in} \onehalfspacing % 调整章节标题格式 \titleformat{\section}{\large\bfseries}{\thesection}{1em}{} \titleformat{\subsection}{\normalsize\bfseries}{\thesubsection}{1em}{} % 论文信息 \title{Sieve of Eratosthenes} \author{Zhang Hongwei} \date{December 2, 2025} \begin{document} \maketitle \begin{abstract} This paper describes the Sieve of Eratosthenes, an ancient algorithm for identifying all prime numbers up to a given limit $ n $. The method works by iteratively marking the multiples of each prime starting from 2. We outline its procedure, justify key optimizations, analyze time and space complexity, and compare it with modern variants. A flowchart is included to illustrate the execution process. \end{abstract} \section{Introduction} Finding all primes less than or equal to $ n $ is a basic problem in number theory. While checking individual numbers for primality can be done by trial division, generating many primes efficiently requires a different approach. The Sieve of Eratosthenes, attributed to the Greek mathematician Eratosthenes in the 3rd century BCE, provides a simple and effective solution. It avoids expensive divisibility tests by eliminating composite numbers through multiplication: once a number is identified as prime, all of its multiples are marked as non-prime. Given a positive integer $ n $, the algorithm produces all primes $ \leq n $. Its time complexity is $ O(n \log \log n) $, and it uses $ O(n) $ memory. This makes it practical for $ n $ up to several million on modern computers. \section{Basic Idea} A prime number has no divisors other than 1 and itself. The sieve exploits the fact that every composite number must have at least one prime factor not exceeding its square root. Starting with a list of integers from 2 to $ n $, we proceed as follows: \begin{itemize} \item Mark 2 as prime, then mark all multiples of 2 greater than $ 2^2 = 4 $ as composite. \item Move to the next unmarked number (3), mark it as prime, and eliminate multiples starting from $ 3^2 = 9 $. \item Repeat this process for each new prime $ p $ until $ p > \sqrt{n} $. \end{itemize} After completion, all unmarked numbers are prime. \subsection*{Why start from $ p^2 $?} Any multiple of $ p $ less than $ p^2 $, say $ k \cdot p $ where $ k < p $, would have already been marked when processing smaller primes. For example, $ 6 = 2 \times 3 $ is removed during the pass for 2. Thus, there's no need to revisit these values. \subsection*{Why stop at $ \sqrt{n} $?} If a number $ m \leq n $ is composite, it can be written as $ m = a \cdot b $, with $ 1 < a \leq b $. Then: \[ a^2 \leq a \cdot b = m \leq n \quad \Rightarrow \quad a \leq \sqrt{n}. \] So $ m $ must have a prime factor $ \leq \sqrt{n} $. Therefore, scanning beyond $ \sqrt{n} $ is unnecessary. \section{Implementation Steps} Consider $ n = 100 $. We use a boolean array \texttt{prime[0..100]}, initialized to \texttt{true}. Set \texttt{prime[0]} and \texttt{prime[1]} to \texttt{false}. \begin{enumerate} \item Start with $ p = 2 $. Since \texttt{prime[2]} is true, mark $ 4, 6, 8, \dots, 100 $ as false. \item Next, $ p = 3 $ is unmarked. Mark $ 9, 15, 21, \dots $ (odd multiples $ \geq 9 $). \item $ p = 4 $ is already marked; skip. \item $ p = 5 $ is prime. Mark $ 25, 35, 45, \dots $ \item $ p = 7 $: mark $ 49, 77, 91 $ \item $ p = 11 > \sqrt{100} $, so stop. \end{enumerate} All indices $ i \geq 2 $ where \texttt{prime[i] == true} are prime. \begin{figure}[h!] \centering \includegraphics[width=0.7\linewidth]{Flowchart.jpg} \caption{Flowchart of the Sieve of Eratosthenes algorithm} \label{fig:flowchart} \end{figure} Figure~\ref{fig:flowchart} shows the control flow: initialization, loop over $ p $ from 2 to $ \sqrt{n} $, and marking multiples starting at $ p^2 $. \section{Complexity Analysis} \subsection{Time Usage} For each prime $ p \leq \sqrt{n} $, we mark about $ n/p $ elements. Summing over such $ p $: \[ T(n) \approx n \sum_{\substack{p \leq \sqrt{n} \\ p\ \text{prime}}} \frac{1}{p}. \] It is known from number theory that the sum of reciprocals of primes up to $ x $ grows like $ \log \log x $. So: \[ \sum_{p \leq \sqrt{n}} \frac{1}{p} \sim \log \log \sqrt{n} = \log(\tfrac{1}{2}\log n) = \log \log n + \log \tfrac{1}{2} \approx \log \log n. \] Hence, total time is $ O(n \log \log n) $. \subsection{Memory Requirement} The algorithm requires one boolean value per integer from 0 to $ n $, leading to $ O(n) $ space usage. \section{Variants and Practical Considerations} \begin{table}[h!] \centering \caption{Common methods for generating primes} \label{tab:methods} \begin{tabular}{|l|c|c|l|} \hline Method & Time & Space & Remarks \\ \hline Trial division (single number) & $O(\sqrt{n})$ & $O(1)$ & Simple, slow for batches \\ Standard sieve & $O(n \log \log n)$ & $O(n)$ & Good for $ n \leq 10^7 $ \\ Segmented sieve & $O(n \log \log n)$ & $O(\sqrt{n})$ & Reduces memory usage \\ Linear sieve (Euler) & $O(n)$ & $O(n)$ & Faster in theory, more complex \\ \hline \end{tabular} \end{table} In practice, the standard sieve performs well due to good cache behavior and low constant factors. For very large $ n $, segmented versions divide the range into blocks processed separately. The linear sieve improves asymptotic time by ensuring each composite is crossed off exactly once using its smallest prime factor, but the overhead often negates benefits for moderate inputs. \section{Conclusion} The Sieve of Eratosthenes remains a fundamental tool in algorithm design. Its simplicity allows easy implementation and teaching, while its efficiency supports real-world applications in cryptography, number theory, and data processing. Although newer algorithms exist, the original sieve continues to be relevant—especially when clarity and reliability matter more than marginal speed gains. With minor improvements, it scales well within typical computational limits. \section{References} \begin{thebibliography}{9} \bibitem{knuth} Donald E. Knuth. \textit{The Art of Computer Programming, Volume 2: Seminumerical Algorithms}. 3rd Edition, Addison-Wesley, 1997. ISBN: 0-201-89684-2. (See Section 4.5.4 for discussion of prime number sieves.) \bibitem{hardy} G. H. Hardy and E. M. Wright. \textit{An Introduction to the Theory of Numbers}. 6th Edition, Oxford University Press, 2008. ISBN: 978-0-19-921986-5. (Chapter 1 discusses prime numbers and includes historical notes on Eratosthenes.) \bibitem{pomerance} Carl Pomerance. \newblock “A Tale of Two Sieves.” \newblock \textit{Notices of the American Mathematical Society}, vol.~43, no.~12, pp.~1473–1485, December 1996. Available online: \url{https://www.ams.org/journals/notices/199612/199612FullIssue.pdf#page=1473} \bibitem{crandall} Richard Crandall and Carl Pomerance. \textit{Prime Numbers: A Computational Perspective}. 2nd Edition, Springer, 2005. ISBN: 978-0-387-25282-7. (A detailed treatment of sieve methods including Eratosthenes and segmented variants.) \bibitem{eratosthenes-original} Thomas L. Heath (Ed.). \textit{Greek Mathematical Works, Volume II: From Aristarchus to Pappus}. Harvard University Press (Loeb Classical Library), 1941. ISBN: 978-0-674-99396-7. (Contains surviving fragments and references to Eratosthenes’ work in ancient sources.) \end{thebibliography} \end{document} 修改错误 ,并且增加字数在2000字左右
最新发布
12-03
#!/usr/bin/env python """ Defines a CLI for compiling Sass (both default and themed) into CSS. Should be run from the root of edx-platform using `npm run` wrapper. Requirements for this scripts are stored in requirements/edx/assets.in. Get more details: npm run compile-sass -- --help npm run compile-sass -- --dry Setup (Tutor and Devstack will do this for you): python -m venv venv . venv/bin/activate pip install -r requirements/edx/assets.txt Usage: npm run compile-sass # prod, no args npm run compile-sass -- ARGS # prod, with args npm run compile-sass-dev # dev, no args npm run compile-sass-dev -- ARGS # dev, with args This script is intentionally implemented in a very simplistic way. It prefers repetition over abstraction, and its dependencies are minimal (just click and libsass-python, ideally). We do this because: * If and when we migrate from libsass-python to something less ancient like node-sass or dart-sass, we will want to re-write this script in Bash or JavaScript so that it can work without any backend tooling. By keeping the script dead simple, that will be easier. * The features this script supports (legacy frontends & comprehensive theming) are on the way out, in favor of micro-frontends, branding, and Paragon design tokens. We're not sure how XBlock view styling will fit into that, but it probably can be much simpler than comprehensive theming. So, we don't need this script to be modular and extensible. We just need it to be obvious, robust, and easy to maintain until we can delete it. See docs/decisions/0017-reimplement-asset-processing.rst for more details. """ from __future__ import annotations import glob import os import subprocess import sys from pathlib import Path import click # Accept both long- and short-forms of these words, but normalize to long form. # We accept both because edx-platform asset build scripts historically use the short form, # but NODE_ENV uses the long form, so to make them integrate more seamlessly we accept both. NORMALIZED_ENVS = { "prod": "production", "dev": "development", "production": "production", "development": "development", } @click.option( "-T", "--theme-dir", "theme_dirs", metavar="PATH", multiple=True, envvar="COMPREHENSIVE_THEME_DIRS", type=click.Path(path_type=Path), help=( "Consider sub-dirs of PATH as themes. " "Multiple theme dirs are accepted. " "If none are provided, we look at colon-separated paths on the COMPREHENSIVE_THEME_DIRS env var." ), ) @click.option( "-t", "--theme", "themes", metavar="NAME", multiple=True, type=str, help=( "A theme to compile. " "NAME should be a sub-dir of a PATH provided by --theme-dir. " "Multiple themes are accepted. " "If none are provided, all available themes are compiled." ), ) @click.option( "--skip-default", is_flag=True, help="Don't compile default Sass.", ) @click.option( "--skip-themes", is_flag=True, help="Don't compile any themes (overrides --theme* options).", ) @click.option( "--skip-lms", is_flag=True, help="Don't compile any LMS Sass.", ) @click.option( "--skip-cms", is_flag=True, help="Don't compile any CMS Sass.", ) @click.option( "--env", type=click.Choice(["dev", "development", "prod", "production"]), default="prod", help="Optimize CSS for this environment. Defaults to 'prod'.", ) @click.option( "--dry", is_flag=True, help="Print what would be compiled, but don't compile it.", ) @click.option( "-h", "--help", "show_help", is_flag=True, help="Print this help.", ) @click.command() @click.pass_context def main( context: click.Context, theme_dirs: list[Path], themes: list[str], skip_default: bool, skip_themes: bool, skip_lms: bool, skip_cms: bool, env: str, dry: bool, show_help: bool, ) -> None: """ Compile Sass for edx-platform and its themes. Default Sass is compiled unless explicitly skipped. Additionally, any number of themes may be specified using --theme-dir and --theme. Default CSS is compiled to css/ directories in edx-platform. Themed CSS is compiled to css/ directories in their source themes. """ def compile_sass_dir( message: str, source_root: Path, target_root: Path, includes: list[Path], tolerate_missing: bool = False, ) -> None: """ Compile a directory of Sass into a target CSS directory, and generate any missing RTL CSS. Structure of source dir is mirrored in target dir. IMPLEMENTATION NOTES: ===================== libsass is a C++ library for compiling Sass (ref: https://github.com/sass/libsass). libsass-python is a small PyPI package wrapping libsass, including: * The `_sass` module, which provides direct Python bindings for the C++ library. (ref: https://github.com/sass/libsass-python/blob/0.10.0/pysass.cpp) * The `sass` module, which adds some friendly Pythonic wrapper functions around `_sass`, notably `sass.compile_dirname(...)`. (ref: https://github.com/sass/libsass-python/blob/0.10.0/sass.py#L198-L201) Our legacy Sass code only works with a super old version of libsass (3.3.2,) which is provided to us by a super old version of libsass-python (0.10.0). In this super old libsass-python version: * the `sass` module DOESN'T support Python 3.11+, but * the `_sass` module DOES support Python 3.11+. Upgrading our Sass to work with newer a libsass version would be arduous and would potentially break comprehensive themes, so we don't want to do that. Forking libsass-python at v0.10.0 and adding Python 3.11+ support would mean adding another repo to the openedx org. Rather than do either of those, we've decided to hack around the problem by just reimplementing what we need of `sass.compile_dirname` here, directly on top of the `_sass` C++ binding module. Eventually, we may eschew libsass-python altogether by switching to SassC@3.3.2, a direct CLI for libsass@3.3.2. (ref: https://github.com/sass/sassc). This would be nice because it would allow us to remove Python from the Sass build pipeline entirely. However, it would mean explicitly compiling & installing both libsass and SassC within the edx-platform build environment, which has its own drawbacks. """ # Constants from libsass-python SASS_STYLE_NESTED = 0 _SASS_STYLE_EXPANDED = 1 _SASS_STYLE_COMPACT = 2 SASS_STYLE_COMPRESSED = 3 SASS_COMMENTS_NONE = 0 SASS_COMMENTS_LINE_NUMBERS = 1 # Defaults from libass-python precision = 5 source_map_filename = None custom_functions = [] importers = None use_dev_settings: bool = NORMALIZED_ENVS[env] == "development" fs_encoding: str = sys.getfilesystemencoding() or sys.getdefaultencoding() output_style: int = SASS_STYLE_NESTED if use_dev_settings else SASS_STYLE_COMPRESSED source_comments: int = SASS_COMMENTS_LINE_NUMBERS if use_dev_settings else SASS_COMMENTS_NONE include_paths: bytes = os.pathsep.join(str(include) for include in includes).encode(fs_encoding) click.secho(f" {message}...", fg="cyan") click.secho(f" Source: {source_root}") click.secho(f" Target: {target_root}") if not source_root.is_dir(): if tolerate_missing: click.secho(f" Skipped because source directory does not exist.", fg="yellow") return else: raise FileNotFoundError(f"missing Sass source dir: {source_root}") click.echo(f" Include paths:") for include in includes: click.echo(f" {include}") click.echo(f" Files:") for dirpath, _, filenames in os.walk(str(source_root)): for filename in filenames: if filename.startswith('_'): continue if not filename.endswith(('.scss', '.sass')): continue source = Path(dirpath) / filename target = (target_root / source.relative_to(source_root)).with_suffix('.css') click.echo(f" {source} -> {target}") if not dry: # Import _sass late so that this script can be dry-run without installing # libsass, which takes a while as it must be compiled from its C source. from _sass import compile_filename # pylint: disable=protected-access success, output, _ = compile_filename( str(source).encode(fs_encoding), output_style, source_comments, include_paths, precision, source_map_filename, custom_functions, importers, ) output_text = output.decode('utf-8') if not success: raise Exception(f"Failed to compile {source}: {output_text}") target.parent.mkdir(parents=True, exist_ok=True) with open(target, 'w', encoding="utf-8") as target_file: target_file.write(output_text) click.secho(f" Done.", fg="green") # For Sass files without explicit RTL versions, generate # an RTL version of the CSS using the rtlcss library. for sass_path in glob.glob(str(source_root) + "/**/*.scss"): if Path(sass_path).name.startswith("_"): # Don't generate RTL CSS for partials continue if sass_path.endswith("-rtl.scss"): # Don't generate RTL CSS if the file is itself an RTL version continue if Path(sass_path.replace(".scss", "-rtl.scss")).exists(): # Don't generate RTL CSS if there is an explicit Sass version for RTL continue click.echo(" Generating missing right-to-left CSS:") source_css_file = sass_path.replace(str(source_root), str(target_root)).replace( ".scss", ".css" ) target_css_file = source_css_file.replace(".css", "-rtl.css") click.echo(f" Source: {source_css_file}") click.echo(f" Target: {target_css_file}") if not dry: subprocess.run(["rtlcss", source_css_file, target_css_file]) click.secho(" Generated.", fg="green") # Information click.secho(f"USING ENV: {NORMALIZED_ENVS[env]}", fg="blue") if dry: click.secho(f"DRY RUN: Will print compile steps, but will not compile anything.", fg="blue") click.echo() # Warnings if show_help: click.echo(context.get_help()) return if skip_lms and skip_cms: click.secho("WARNING: You are skipping both LMS and CMS... nothing will be compiled!", fg="yellow") if skip_default and skip_themes: click.secho("WARNING: You are skipped both default Sass and themed Sass... nothing will be compiled!", fg="yellow") click.echo() # Build a list of theme paths: if skip_themes: theme_paths = [] else: theme_paths = [ theme_dir / theme # For every theme dir, for theme_dir in theme_dirs for theme in ( # for every theme name (if theme names provided), themes or # or for every subdir of theme dirs (if no theme name provided), (theme_dir_entry.name for theme_dir_entry in theme_dir.iterdir()) ) # consider the path a theme if it has a lms/ or cms/ subdirectory. if (theme_dir / theme / "lms").is_dir() or (theme_dir / theme / "cms").is_dir() ] # We expect this script to be run from the edx-platform root. repo = Path(".") if not (repo / "xmodule").is_dir(): # Sanity check: If the xmodule/ folder is missing, we're definitely not at the root # of edx-platform, so save the user some headache by exiting early. raise Exception(f"{__file__} must be run from the root of edx-platform") # Every Sass compilation will use have these directories as lookup paths, # regardless of theme. common_includes = [ repo / "common" / "static", repo / "common" / "static" / "sass", repo / "node_modules" / "@edx", repo / "node_modules", ] if not skip_default: click.secho(f"Compiling default Sass...", fg="cyan", bold=True) if not skip_lms: compile_sass_dir( "Compiling default LMS Sass", repo / "lms" / "static" / "sass", repo / "lms" / "static" / "css", includes=[ *common_includes, repo / "lms" / "static" / "sass" / "partials", repo / "lms" / "static" / "sass", ], ) compile_sass_dir( "Compiling default certificate Sass", repo / "lms" / "static" / "certificates" / "sass", repo / "lms" / "static" / "certificates" / "css", includes=[ *common_includes, repo / "lms" / "static" / "sass" / "partials", repo / "lms" / "static" / "sass", ], ) if not skip_cms: compile_sass_dir( "Compiling default CMS Sass", repo / "cms" / "static" / "sass", repo / "cms" / "static" / "css", includes=[ *common_includes, repo / "lms" / "static" / "sass" / "partials", repo / "cms" / "static" / "sass" / "partials", repo / "cms" / "static" / "sass", ], ) click.secho(f"Done compiling default Sass!", fg="cyan", bold=True) click.echo() for theme in theme_paths: click.secho(f"Compiling Sass for theme at {theme}...", fg="cyan", bold=True) if not skip_lms: compile_sass_dir( "Compiling default LMS Sass with themed partials", repo / "lms" / "static" / "sass", theme / "lms" / "static" / "css", includes=[ *common_includes, theme / "lms" / "static" / "sass" / "partials", repo / "lms" / "static" / "sass" / "partials", repo / "lms" / "static" / "sass", ], tolerate_missing=True, ) compile_sass_dir( "Compiling themed LMS Sass as overrides to CSS from previous step", theme / "lms" / "static" / "sass", theme / "lms" / "static" / "css", includes=[ *common_includes, theme / "lms" / "static" / "sass" / "partials", repo / "lms" / "static" / "sass" / "partials", repo / "lms" / "static" / "sass", ], tolerate_missing=True, ) compile_sass_dir( "Compiling themed certificate Sass", theme / "lms" / "static" / "certificates" / "sass", theme / "lms" / "static" / "certificates" / "css", includes=[ *common_includes, theme / "lms" / "static" / "sass" / "partials", theme / "lms" / "static" / "sass", ], tolerate_missing=True, ) if not skip_cms: compile_sass_dir( "Compiling default CMS Sass with themed partials", repo / "cms" / "static" / "sass", theme / "cms" / "static" / "css", includes=[ *common_includes, repo / "lms" / "static" / "sass" / "partials", theme / "cms" / "static" / "sass" / "partials", repo / "cms" / "static" / "sass" / "partials", repo / "cms" / "static" / "sass", ], tolerate_missing=True, ) compile_sass_dir( "Compiling themed CMS Sass as overrides to CSS from previous step", theme / "cms" / "static" / "sass", theme / "cms" / "static" / "css", includes=[ *common_includes, repo / "lms" / "static" / "sass" / "partials", theme / "cms" / "static" / "sass" / "partials", repo / "cms" / "static" / "sass" / "partials", repo / "cms" / "static" / "sass", ], tolerate_missing=True, ) click.secho(f"Done compiling Sass for theme at {theme}!", fg="cyan", bold=True) click.echo() # Report what we did. click.secho("Successfully compiled:", fg="green", bold=True) if not skip_default: click.secho(f" - {repo.absolute()} (default Sass)", fg="green") for theme in theme_paths: click.secho(f" - {theme}", fg="green") if skip_lms: click.secho(f"(skipped LMS)", fg="yellow") if skip_cms: click.secho(f"(skipped CMS)", fg="yellow") if __name__ == "__main__": main(prog_name="npm run compile-sass --") python scripts/compile_sass.py --env=development USING ENV: development Compiling default Sass... Compiling default LMS Sass... Source: lms\static\sass Target: lms\static\css Include paths: common\static common\static\sass node_modules\@edx node_modules lms\static\sass\partials lms\static\sass Files: lms\static\sass\lms-course-rtl.scss -> lms\static\css\lms-course-rtl.css lms\static\sass\lms-course.scss -> lms\static\css\lms-course.css lms\static\sass\lms-footer-edx-rtl.scss -> lms\static\css\lms-footer-edx-rtl.css lms\static\sass\lms-footer-edx.scss -> lms\static\css\lms-footer-edx.css lms\static\sass\lms-footer-rtl.scss -> lms\static\css\lms-footer-rtl.css lms\static\sass\lms-footer.scss -> lms\static\css\lms-footer.css lms\static\sass\lms-main-v1-rtl.scss -> lms\static\css\lms-main-v1-rtl.css Traceback (most recent call last): File "C:\Users\chaoguog\Downloads\edx-platform-master\scripts\compile_sass.py", line 451, in <module> main(prog_name="npm run compile-sass --") File "C:\Users\chaoguog\Downloads\edx-platform-master\.venv\Lib\site-packages\click\core.py", line 1442, in __call__ return self.main(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\chaoguog\Downloads\edx-platform-master\.venv\Lib\site-packages\click\core.py", line 1363, in main rv = self.invoke(ctx) ^^^^^^^^^^^^^^^^ File "C:\Users\chaoguog\Downloads\edx-platform-master\.venv\Lib\site-packages\click\core.py", line 1226, in invoke return ctx.invoke(self.callback, **ctx.params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\chaoguog\Downloads\edx-platform-master\.venv\Lib\site-packages\click\core.py", line 794, in invoke return callback(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\chaoguog\Downloads\edx-platform-master\.venv\Lib\site-packages\click\decorators.py", line 34, in new_func return f(get_current_context(), *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\chaoguog\Downloads\edx-platform-master\scripts\compile_sass.py", line 335, in main compile_sass_dir( File "C:\Users\chaoguog\Downloads\edx-platform-master\scripts\compile_sass.py", line 252, in compile_sass_dir raise Exception(f"Failed to compile {source}: {output_text}") Exception: Failed to compile lms\static\sass\lms-main-v1-rtl.scss: Error: File to import not found or unreadable: mixins Parent style sheet: C:/Users/chaoguog/Downloads/edx-platform-master/lms/static/sass/_build-lms-v1.scss on line 81 of lms/static/sass/_build-lms-v1.scss >> @import 'mixins'; ^
09-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值