Strip line and/or block comments from a string. Works with JavaScript, Sass, CSS, Less.js, and a number of other languages.
This repo is a port of strip-comments
The utility receives a file as input and prints its content with comments removed. Handles line comments and/or block comments. Optionally removes the first comment only or ignores protected comments.
Supports:
- ada
- apl
- applescript
- c
- csharp
- css
- hashbang
- haskell
- html
- java
- javascript
- less
- lua
- matlab
- ocaml
- pascal
- perl
- php
- python
- ruby
- sass
- shebang
- sql
- swift
- typscript
- xml
Via pypi (pypi package TBD)
pip install strip-comments
From source
git clone https://github.com/igrekus/strip-comments.git
cd strip-comments
pip install .
By default all comments are stripped.
cat sample-file.js
'use strict';
/* -------------------------
This is the comment body.
*/ -------------------------
const foo = 'bar'; // another line
$ strip-comments sample-file.js
'use strict';
const foo = 'bar';
For more use cases see the command help.
Remove all code comments from the given source
, including protected comments that start with !
, unless keep_protected
is passed true.
Args
source
: str -- input Python string to strip comments fromblock
: bool -- remove block commentsline
: bool -- remove line commentsfirst
: bool -- remove only the first commentlanguage
: str -- programming language the string is written inkeep_protected
: bool -- keep the protected comments (starting with a!
as the first char)preserve_newlines
: bool -- preserve newlines after comments are removed
returns
: str -- modified source string
Example
from strip_comments import strip
print(strip.strip('const foo = "bar";// this is a comment\n /* me too */'))
# >>> const foo = "bar";
Convenience wrapper, remove block comments only.
Example
from strip_comments import strip
print(strip.block('const foo = "bar";// this is a comment\n /* me too */'))
# >>> const foo = "bar";// this is a comment
Convenience wrapper, remove line comments only.
Example
from strip_comments import strip
print(strip.line('const foo = "bar";// this is a comment\n /* me too */'))
# >>> const foo = "bar";\n/* me too */
Convenience wrapper, remove only the first comment from the given source
. If keep_protected
is passed True
, the first non-protected comment will be removed.
Example
from strip_comments import strip
print(strip.first('const foo = "bar"; //! protected\n // removed', keep_protected=True))
# >>> const foo = "bar"; //! protected\n
Contributing
Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.
Running Tests
pip install pytest
pytest tests
Copyright © 2024-present, igrekus. Released under the MIT License.
- port code
- make code pythonic (kinda)
- add CLI entrypoint
- update readme
- add the ability to handle directories on the input
- make a pypi package
- expand other-lang tests
- add lang auto-detect of some sort
- add header banner?
- add fancy badges to readme