Skip to content

Commit

Permalink
feat: add python script to compute supported extensions
Browse files Browse the repository at this point in the history
  • Loading branch information
shipurjan committed Jan 14, 2024
1 parent b6473ed commit 00b4215
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 66 deletions.
23 changes: 14 additions & 9 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ jobs:
VERSION=${GITHUB_REF_NAME#v}
echo Version: $VERSION
echo "VERSION=$VERSION" >> $GITHUB_ENV
- run: sudo apt-get update -y && sudo apt-get install tree zip -y

- name: Show directory tree before build
run: tree
Expand All @@ -71,24 +73,30 @@ jobs:
with:
go-version: '1.21.5'

- name: Test
run: go test -v ./...

- name: Create artifacts directory
run: mkdir artifacts

- name: Install dependencies
run: |
sudo apt-get update
sudo apt-get install -y musl-dev gcc
- uses: actions/setup-python@v5
with:
python-version: '3.11'

- name: Build for different platforms
run: |
PLATFORMS=($(go tool dist list | grep -E '^windows|^linux/(amd64|arm|386)|^darwin'))
SUPPORTED_EXTENSIONS=$(python scripts/compute_supported_extensions.py)
LDFLAGS="-X 'main.supported_extensions=$SUPPORTED_EXTENSIONS' -X 'main.version=$VERSION'"
for PLATFORM in "${PLATFORMS[@]}"
do
arr=(${PLATFORM//\// })
echo "${arr[0]}/${arr[1]}"
GOOS=${arr[0]} GOARCH=${arr[1]} bash -c '\
go build -o out/ -ldflags "-X main.version=${VERSION}" &&
GOOS=${arr[0]} GOARCH=${arr[1]} FLAGS=$LDFLAGS bash -c '
go build -o out/ -ldflags "$FLAGS" &&
echo "$LDFLAGS" &&
cp {LICENSE,README.md} out/ &&
zip -j artifacts/${{ github.event.repository.name }}_$GOOS-$GOARCH.zip out/*
rm -rf out/*'
Expand All @@ -97,9 +105,6 @@ jobs:
- name: Show directory tree after build
run: tree

- name: Test
run: go test -v ./...

- name: Upload Build Artifact
uses: actions/[email protected]
with:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
*.srt
*.lrc
*.mp3
*.exe
.vscode/
.githubvars
main
Expand Down
6 changes: 5 additions & 1 deletion .husky/hooks/pre-push
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,12 @@ TAG=$(git tag --points-at HEAD)
exit 0
}

echo "Computing supported extensions..."
SUPPORTED_EXTENSIONS=$(python scripts/compute_supported_extensions.py)
echo "Found supported extensions:" $SUPPORTED_EXTENSIONS

echo "Building..."
go build -o out/subtitle-to-lrc -ldflags "-X main.version=${TAG:1}"
go build -o out/subtitle-to-lrc -ldflags "-X 'main.version=${TAG:1}' -X 'main.supported_extensions=${SUPPORTED_EXTENSIONS}'"

echo "Updating README.md..."
python scripts/update_readme.py out/subtitle-to-lrc
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# subtitle-to-lrc 0.1.1
# subtitle-to-lrc 0.1.0

[![GPLv3 License](https://img.shields.io/badge/License-GPL%20v3-yellow.svg)](https://opensource.org/licenses/)
[![Build and release](https://github.com/shipurjan/subtitle-to-lrc/actions/workflows/go.yml/badge.svg)](https://github.com/shipurjan/subtitle-to-lrc/actions/workflows/go.yml)
Expand Down Expand Up @@ -26,7 +26,7 @@ USAGE:
[output-file] - if not provided the program will use <input-file> filename with its extension replaced by .lrc
VERSION:
0.1.1
0.1.0
AUTHOR:
Cyprian Zdebski <[email protected]>
Expand Down
28 changes: 3 additions & 25 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,40 +15,18 @@ import (
)

var (
version string
version string
supported_extensions string
)

func filter[T any](ss []T, test func(T) bool) (ret []T) {
for _, s := range ss {
if test(s) {
ret = append(ret, s)
}
}
return
}

func main() {
files, err := os.ReadDir("./converter")
if err != nil {
fmt.Println("[ERROR]", err)
}
converter_folders := filter(files, func(file os.DirEntry) bool {
return file.IsDir() && file.Name() != "shared"
})

directory_names := make([]string, 0, len(converter_folders))
for _, folder := range converter_folders {
directory_names = append(directory_names, folder.Name())
}
allowed_extensions := strings.Join(directory_names, ", ")

app := &cli.App{
Name: "subtitle-to-lrc",
Version: version,
Usage: "Convert subtitle files to .lrc format",
UsageText: "subtitle-to-lrc [options] <input-file> [output-file]\n" +
"\n" +
"<input-file> - the file must have an allowed subtitle extension (" + allowed_extensions + ")\n" +
"<input-file> - the file must have an allowed subtitle extension (" + supported_extensions + ")\n" +
"[output-file] - if not provided the program will use <input-file> filename with its extension replaced by .lrc",
Compiled: time.Now(),
EnableBashCompletion: true,
Expand Down
1 change: 1 addition & 0 deletions scripts/README.dev.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Always call python scripts from the base repository directory
26 changes: 26 additions & 0 deletions scripts/compute_supported_extensions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import glob
import os
from pathlib import Path
import sys


def error(msg=''):
print(f'[ERROR] {msg}')
sys.exit(1)


def ok(msg=''):
print(f'[OK] {msg}')
sys.exit(0)


def main():
supported_extensions = [
os.path.basename(Path(dir)) for dir in glob.glob('./converter/*/')
if os.path.basename(Path(dir)) != 'shared'
]
print(', '.join(supported_extensions))


if __name__ == '__main__':
main()
81 changes: 52 additions & 29 deletions scripts/update_readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,58 @@
import subprocess
import re

if len(sys.argv) < 2:
print(f'Usage: python {os.path.basename(__file__)} <path to out binary>')

def error(msg=''):
print(f'[ERROR] {msg}')
sys.exit(1)

bin_path = os.path.abspath(Path(sys.argv[1]))

help_output = subprocess.check_output([bin_path, '--help']).decode('utf-8')
usage = "```text\n" + help_output + "\n```"
version_output = subprocess.check_output([bin_path, '--version']).decode('utf-8')
if 'flag provided but not defined' in version_output:
print(version_output)
sys.exit(1)
version = version_output[version_output.find('version ') + len('version '):]
allowed_extensions = [re.search('\(([^)]+)', i).group(1).split(', ') for i in help_output.splitlines() if i.strip().startswith('<input-file>')][0]
supported_extensions = ''.join([f'\n* `.{i}`' for i in allowed_extensions])

readme = None
if Path('README.stub').exists():
with open('README.stub') as f:
readme_stub = f.read()
readme = readme_stub
readme = readme.replace('{VERSION}', version)
readme = readme.replace('{SUPPORTED_EXTENSIONS}', supported_extensions)
readme = readme.replace('{USAGE}', usage)
readme = readme.strip()

if not readme:
raise Exception('README.stub produces empty readme')

with open('README.md', 'w') as f:
f.write(readme)
print('[OK]')
def ok(msg=''):
print(f'[OK] {msg}')
sys.exit(0)


def main():
if len(sys.argv) < 2:
error(
f'Usage: python {os.path.basename(__file__)} <path to out binary>')

bin_path = os.path.abspath(Path(sys.argv[1]))

help_output = subprocess.check_output([bin_path, '--help']).decode('utf-8')
version_output = subprocess.check_output(
[bin_path, '--version']).decode('utf-8')

if 'flag provided but not defined' in version_output:
error(version_output)

usage = "```text\n" + help_output + "\n```"
version = version_output[version_output.find(
'version ') + len('version '):]
supported_extensions = [re.search('\(([^)]+)', i).group(1).split(', ')
for i in help_output.splitlines() if i.strip().startswith('<input-file>')][0]
supported_extensions_str = ''.join(
[f'\n* `.{i}`' for i in supported_extensions])

readme = None
if Path('README.stub').exists():
with open('README.stub') as f:
readme_stub = f.read()

readme = readme_stub
readme = readme.replace('{VERSION}', version)
readme = readme.replace(
'{SUPPORTED_EXTENSIONS}', supported_extensions_str)
readme = readme.replace('{USAGE}', usage)
readme = readme.strip()

if not readme:
error('README.stub produces empty readme')

with open('README.md', 'w') as f:
f.write(readme)
ok('README.md updated')


if __name__ == '__main__':
main()

0 comments on commit 00b4215

Please sign in to comment.