Skip to content

Instantly share code, notes, and snippets.

@weibeu
Created August 10, 2020 12:21
Show Gist options
  • Save weibeu/c661250ca71d6e1f13f9406455eb2201 to your computer and use it in GitHub Desktop.
Save weibeu/c661250ca71d6e1f13f9406455eb2201 to your computer and use it in GitHub Desktop.
Love open source? This basic scripts lets you inject license into your all source files.

License Injector

Injects license into your all source files.

Basic Usage

Assuming you have Python project and LICENSE file in project root.

  • Download the script and move it to your project root.
  • Execute the script double click or however you prefer.

Use as command line tool

$ inject_license.py [Project root] [Path to license file] [file with extensions to consider ...]
#!/usr/bin/env python3
import os
# import fnmatch
def format_license(license):
clean_license = license.strip("\n").strip()
if not (clean_license.startswith('"""') and clean_license.endswith('"""')):
license = '"""\n{}\n\n"""\n\n\n'.format(clean_license)
return license
def get_license(path):
with open(path) as f:
return format_license(f.read())
# TODO: Ignore .gitignore.
def get_gitignores(path):
with open(path) as f:
return f.readlines()
def inject_license(path, license):
try:
with open(path, "r", encoding="utf-8") as f:
content = f.read()
with open(path, "w", encoding="utf-8") as f:
f.write(license + content)
except UnicodeDecodeError:
print("--- !! Skipped file {} ---".format(path))
def inject(base_dir, license=None, extensions=["py"]):
base_dir = os.path.abspath(base_dir)
if not license:
for file in os.listdir(base_dir):
if file.upper().startswith("LICENSE"):
license = os.path.join(base_dir, file)
break
if not license:
raise FileNotFoundError("Couldn't find LICENSE file in root.")
if not os.path.isabs(license):
license = os.path.join(base_dir, license)
license = get_license(license)
for root, dirs, files in os.walk(base_dir):
for file in files:
try:
if file.split(".")[-1] not in extensions:
continue
except IndexError:
continue
path = os.path.join(base_dir, root, file)
inject_license(path, license)
if __name__ == "__main__":
import sys
base = os.path.abspath(os.getcwd())
license = None
try:
base = sys.argv[1]
except IndexError:
pass
try:
license = sys.argv[2]
except IndexError:
pass
extensions = sys.argv[3:] or ["py"]
inject(base, license=license, extensions=extensions)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment