Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line numberDiff line numberDiff line change
Expand Up@@ -69,6 +69,9 @@ A brief description of the categories of changes:
`__test__.py` exists in the same package. Previously in these cases there
would only be one test target made.

* (gazelle) If a non-test Python file contains `if __name__ == "__main__":`,
then a `py_binary` target is made for it instead of a `py_library` target.

Breaking changes:

* (pip) `pip_install` repository rule in this release has been disabled and
Expand Down
47 changes: 34 additions & 13 deletions gazelle/python/generate.go
Original file line numberDiff line numberDiff line change
Expand Up@@ -20,6 +20,7 @@ import (
"log"
"os"
"path/filepath"
"regexp"
"strings"

"github.com/bazelbuild/bazel-gazelle/config"
Expand DownExpand Up@@ -85,14 +86,11 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes

packageName := filepath.Base(args.Dir)

pyBinaryFilenames := treeset.NewWith(godsutils.StringComparator)
pyLibraryFilenames := treeset.NewWith(godsutils.StringComparator)
pyTestFilenames := treeset.NewWith(godsutils.StringComparator)
pyFileNames := treeset.NewWith(godsutils.StringComparator)

// hasPyBinary controls whether a py_binary target should be generated for
// this package or not.
hasPyBinary := false

// hasPyTestEntryPointFile and hasPyTestEntryPointTarget control whether a py_test target should
// be generated for this package or not.
hasPyTestEntryPointFile := false
Expand All@@ -106,14 +104,14 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
ext := filepath.Ext(f)
if ext == ".py" {
pyFileNames.Add(f)
if !hasPyBinary && f == pyBinaryEntrypointFilename {
hasPyBinary = true
} else if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
if !hasPyTestEntryPointFile && f == pyTestEntrypointFilename {
hasPyTestEntryPointFile = true
} else if f == conftestFilename {
hasConftestFile = true
} else if strings.HasSuffix(f, "_test.py") || strings.HasPrefix(f, "test_") {
pyTestFilenames.Add(f)
} else if f == pyBinaryEntrypointFilename || hasNameEqualsMain(filepath.Join(args.Config.RepoRoot, args.Rel, f)) {
pyBinaryFilenames.Add(f)
} else {
pyLibraryFilenames.Add(f)
}
Expand DownExpand Up@@ -270,13 +268,19 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
appendPyLibrary(pyLibraryFilenames, cfg.RenderLibraryName(packageName))
}

if hasPyBinary {
deps, err := parser.parseSingle(pyBinaryEntrypointFilename)
pyBinaryFilenames.Each(func(index int, filename interface{}) {
entrypointFilename := filename.(string)
deps, err := parser.parseSingle(entrypointFilename)
if err != nil {
log.Fatalf("ERROR: %v\n", err)
}

pyBinaryTargetName := cfg.RenderBinaryName(packageName)
var pyBinaryTargetName string
if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTargetName = cfg.RenderBinaryName(packageName)
} else {
pyBinaryTargetName = strings.TrimSuffix(filepath.Base(filename.(string)), ".py")
}

// Check if a target with the same name we are generating already
// exists, and if it is of a different kind from the one we are
Expand All@@ -296,17 +300,20 @@ func (py *Python) GenerateRules(args language.GenerateArgs) language.GenerateRes
}

pyBinaryTarget := newTargetBuilder(pyBinaryKind, pyBinaryTargetName, pythonProjectRoot, args.Rel, pyFileNames).
setMain(pyBinaryEntrypointFilename).
addVisibility(visibility).
addSrc(pyBinaryEntrypointFilename).
addSrc(entrypointFilename).
addModuleDependencies(deps).
generateImportsAttribute()

if entrypointFilename == pyBinaryEntrypointFilename {
pyBinaryTarget.setMain(pyBinaryEntrypointFilename)
}

pyBinary := pyBinaryTarget.build()

result.Gen = append(result.Gen, pyBinary)
result.Imports = append(result.Imports, pyBinary.PrivateAttr(config.GazelleImportsKey))
}
})

var conftest *rule.Rule
if hasConftestFile {
Expand DownExpand Up@@ -463,6 +470,20 @@ func hasEntrypointFile(dir string) bool {
return false
}

// hasNameEqualsMain determines if the file contains 'if __name__ == "__main__"'.
func hasNameEqualsMain(path string) bool {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally think that this new feature needs a feature toggle. There should be a gazelle directive that enables the behaviour.

What is more, sometimes developers add if __name__ in order to test the script locally but do not intend to create a binary target for others to consume. I wonder if in those cases we should be able to say in the python file:

if __name__ == "__main__": # gazelle: ignore
main()

@adzenithadzenithNov 17, 2023

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A feature toggle is a great call. Let me look into making that work.

As for the ignore, is there any reason you wouldn't want that to get moved to a py_binary? Then you could bazel run it and test it locally. (If the script is already in a test target, then this change won't move it - it only moves scripts from py_library -> py_binary, not from py_test, because you can already bazel run a test.) I guess I'm just curious when you might want an ignore / might want to keep a script out of a py_binary target.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's keep the ignore part out of scope for now. It probably does not need to be supported in the initial version.

searchString := `if __name__ == ['"]__main__['"]:`
bytesContents, err := os.ReadFile(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right now we are reading the python files once to get the imports and here it would be for once more to check if there is an if __name__ == "main" which may not scale well in super large repos because we have now twice the number of files to process.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let me see how the read to get the import works. Maybe I can figure out a way to not read it twice.

if err != nil {
return false
}
match, err := regexp.Match(searchString, bytesContents)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading from the end of the file line by line in reverse and matching the whole line (stripped) could be faster? If you want to still use regexp, you could at least compile the regexp upfront and store it as a var at the top of the file.

Copy link
Copy Markdown
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, let me look into making this faster.

if err == nil {
return match
}
return false
}

// isEntrypointFile returns whether the given path is an entrypoint file. The
// given path can be absolute or relative.
func isEntrypointFile(path string) bool {
Expand Down
Empty file.
35 changes: 35 additions & 0 deletions gazelle/python/testdata/binary_targets/BUILD.out
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
load("@rules_python//python:defs.bzl", "py_binary", "py_library", "py_test")

py_library(
name = "binary_targets",
srcs = [
"bar.py",
"baz.py",
],
visibility = ["//:__subpackages__"],
)

py_binary(
name = "bar_binary",
srcs = ["bar_binary.py"],
visibility = ["//:__subpackages__"],
deps = [":binary_targets"],
)

py_binary(
name = "single_quote_main",
srcs = ["single_quote_main.py"],
visibility = ["//:__subpackages__"],
deps = [":bar_test"],
)
Comment thread
adzenith marked this conversation as resolved.

py_test(
name = "bar_test",
srcs = ["bar_test.py"],
deps = [":bar_binary"],
)

py_test(
name = "name_main_test",
srcs = ["name_main_test.py"],
)
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/README.md
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
# Binary targets

This test case generates `py_binary` targets for files containing
`if __name__ == "__main__"`.
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/WORKSPACE
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
# This is a Bazel workspace for the Gazelle test data.
Empty file.
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/bar_binary.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar

if __name__ == "__main__":
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/bar_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
import bar_binary
Empty file.
3 changes: 3 additions & 0 deletions gazelle/python/testdata/binary_targets/name_main_test.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
# This should make a py_test target because of the filename
if __name__ == "__main__":
pass
4 changes: 4 additions & 0 deletions gazelle/python/testdata/binary_targets/single_quote_main.py
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
import bar_test

if __name__ == '__main__':
pass
1 change: 1 addition & 0 deletions gazelle/python/testdata/binary_targets/test.yaml
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
---