Skip to content

Add support for pie #587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 30, 2025
Merged
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
2 changes: 2 additions & 0 deletions commands/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ func CommonCommands() []*console.Command {
localCommands := []*console.Command{
binConsoleWrapper,
composerWrapper,
pieWrapper,
phpWrapper,
bookCheckReqsCmd,
bookCheckoutCmd,
Expand Down Expand Up @@ -179,6 +180,7 @@ Environment variables to use Platform.sh/Upsun relationships or Docker services
{{with .Command "composer"}} <info>{{.PreferredName}}</>{{"\t"}}{{.Usage}}{{end}}
{{with .Command "console"}} <info>{{.PreferredName}}</>{{"\t"}}{{.Usage}}{{end}}
{{with .Command "php"}} <info>{{.PreferredName}}</>{{"\t"}}{{.Usage}}{{end}}
{{with .Command "pie"}} <info>{{.PreferredName}}</>{{"\t"}}{{.Usage}}{{end}}

`
}
Expand Down
10 changes: 10 additions & 0 deletions commands/wrappers.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ var (
return console.IncorrectUsageError{ParentError: errors.New(`This command can only be run as "symfony composer"`)}
},
}
pieWrapper = &console.Command{
Usage: "Runs PIE",
Hidden: console.Hide,
// we use an alias to avoid the command being shown in the help but
// still be available for completion
Aliases: []*console.Alias{{Name: "pie"}},
Action: func(c *console.Context) error {
return console.IncorrectUsageError{ParentError: errors.New(`This command can only be run as "symfony pie"`)}
},
}
binConsoleWrapper = &console.Command{
Usage: "Runs the Symfony Console (bin/console) for current project",
Hidden: console.Hide,
Expand Down
24 changes: 0 additions & 24 deletions local/php/composer.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
package php

import (
"bufio"
"bytes"
"crypto/sha512"
"encoding/hex"
Expand Down Expand Up @@ -108,29 +107,6 @@ func Composer(dir string, args, env []string, stdout, stderr, logger io.Writer,
return ComposerResult{}
}

// isPHPScript checks that the composer file is indeed a phar/PHP script (not a .bat file)
func isPHPScript(path string) bool {
if path == "" {
return false
}
file, err := os.Open(path)
if err != nil {
return false
}
defer file.Close()
reader := bufio.NewReader(file)
byteSlice, _, err := reader.ReadLine()
if err != nil {
return false
}

if bytes.Equal(byteSlice, []byte("<?php")) {
return true
}

return bytes.HasPrefix(byteSlice, []byte("#!/")) && bytes.HasSuffix(byteSlice, []byte("php"))
}

func composerVersion() int {
var lock struct {
Version string `json:"plugin-api-version"`
Expand Down
20 changes: 20 additions & 0 deletions local/php/executor.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,26 @@ func (e *Executor) findComposer(extraBin string) (string, error) {
return findComposer(extraBin, e.Logger)
}

// findPie locates the PIE binary depending on the configuration
func (e *Executor) findPie() (string, error) {
if scriptDir, err := e.DetectScriptDir(); err == nil {
for _, file := range []string{"pie.phar", "pie"} {
path := filepath.Join(scriptDir, file)
e.Logger.Debug().Str("source", "PIE").Msgf(`Looking for PIE under "%s"`, path)
d, err := os.Stat(path)
if err != nil {
continue
}
if m := d.Mode(); !m.IsDir() {
e.Logger.Debug().Str("source", "PIE").Msgf(`Found potential PIE as "%s"`, path)
return path, nil
}
}
}

return findPie(e.Logger)
}

// Execute executes the right version of PHP depending on the configuration
func (e *Executor) Execute(loadDotEnv bool) int {
if err := e.Config(loadDotEnv); err != nil {
Expand Down
137 changes: 137 additions & 0 deletions local/php/pie.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
/*
* Copyright (c) 2025-present Fabien Potencier <fabien@symfony.com>
*
* This file is part of Symfony CLI project
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package php

import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"

"github.com/pkg/errors"
"github.com/rs/zerolog"
"github.com/symfony-cli/symfony-cli/util"
)

type PieResult struct {
code int
error error
}

func (p PieResult) Error() string {
if p.error != nil {
return p.error.Error()
}

return ""
}

func (p PieResult) ExitCode() int {
return p.code
}

func Pie(dir string, args, env []string, stdout, stderr, logger io.Writer, debugLogger zerolog.Logger) PieResult {
e := &Executor{
Dir: dir,
BinName: "php",
Stdout: stdout,
Stderr: stderr,
SkipNbArgs: -1,
ExtraEnv: env,
Logger: debugLogger,
}

if piePath := os.Getenv("SYMFONY_PIE_PATH"); piePath != "" {
debugLogger.Debug().Str("SYMFONY_PIE_PATH", piePath).Msg("SYMFONY_PIE_PATH has been defined. User is taking control over PIE detection and execution.")
e.Args = append([]string{piePath}, args...)
} else if path, err := e.findPie(); err == nil && isPHPScript(path) {
e.Args = append([]string{"php", path}, args...)
} else {
reason := "No PIE installation found."
if path != "" {
reason = fmt.Sprintf("Detected PIE file (%s) is not a valid PHAR or PHP script.", path)
}
fmt.Fprintln(logger, " WARNING:", reason)
fmt.Fprintln(logger, " Downloading PIE for you, but it is recommended to install PIE yourself, instructions available at https://github.com/php/pie")
// we don't store it under bin/ to avoid it being found by findPie as we want to only use it as a fallback
binDir := filepath.Join(util.GetHomeDir(), "pie")
if path, err = downloadPie(binDir); err != nil {
return PieResult{
code: 1,
error: errors.Wrap(err, "unable to find pie, get it at https://github.com/php/pie"),
}
}
e.Args = append([]string{"php", path}, args...)
fmt.Fprintf(logger, " (running %s)\n\n", e.CommandLine())
}

ret := e.Execute(false)
if ret != 0 {
return PieResult{
code: ret,
error: errors.Errorf("unable to run %s", e.CommandLine()),
}
}
return PieResult{}
}

func findPie(logger zerolog.Logger) (string, error) {
for _, file := range []string{"pie", "pie.phar"} {
logger.Debug().Str("source", "PIE").Msgf(`Looking for PIE in the PATH as "%s"`, file)
if pharPath, _ := LookPath(file); pharPath != "" {
logger.Debug().Str("source", "PIE").Msgf(`Found potential PIE as "%s"`, pharPath)
return pharPath, nil
}
}

return "", os.ErrNotExist
}

func downloadPie(dir string) (string, error) {
if err := os.MkdirAll(dir, 0755); err != nil {
return "", err
}
path := filepath.Join(dir, "pie.phar")
if _, err := os.Stat(path); err == nil {
return path, nil
}

piePhar, err := downloadPiePhar()
if err != nil {
return "", err
}

err = os.WriteFile(path, piePhar, 0755)
if err != nil {
return "", err
}

return path, nil
}

func downloadPiePhar() ([]byte, error) {
resp, err := http.Get("https://github.com/php/pie/releases/latest/download/pie.phar")
if err != nil {
return nil, err
}
defer resp.Body.Close()
return io.ReadAll(resp.Body)
}
30 changes: 30 additions & 0 deletions local/php/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package php

import (
"bufio"
"bytes"
"os"
)

// isPHPScript checks that the provided file is indeed a phar/PHP script (not a .bat file)
func isPHPScript(path string) bool {
if path == "" {
return false
}
file, err := os.Open(path)
if err != nil {
return false
}
defer file.Close()
reader := bufio.NewReader(file)
byteSlice, _, err := reader.ReadLine()
if err != nil {
return false
}

if bytes.Equal(byteSlice, []byte("<?php")) {
return true
}

return bytes.HasPrefix(byteSlice, []byte("#!/")) && bytes.HasSuffix(byteSlice, []byte("php"))
}
6 changes: 3 additions & 3 deletions local/php/composer_test.go → local/php/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ import (
. "gopkg.in/check.v1"
)

type ComposerSuite struct{}
type UtilsSuite struct{}

var _ = Suite(&ComposerSuite{})
var _ = Suite(&UtilsSuite{})

func (s *ComposerSuite) TestIsComposerPHPScript(c *C) {
func (s *UtilsSuite) TestIsPHPScript(c *C) {
dir, err := filepath.Abs("testdata/php_scripts")
c.Assert(err, IsNil)

Expand Down
18 changes: 13 additions & 5 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,19 @@ func main() {
os.Exit(executor.Execute(false))
}
}
// called via "symfony composer"?
if len(args) >= 2 && args[1] == "composer" {
res := php.Composer("", args[2:], getCliExtraEnv(), os.Stdout, os.Stderr, os.Stderr, terminal.Logger)
terminal.Eprintln(res.Error())
os.Exit(res.ExitCode())
// called via "symfony composer" or "symfony pie"?
if len(args) >= 2 {
if args[1] == "composer" {
res := php.Composer("", args[2:], getCliExtraEnv(), os.Stdout, os.Stderr, os.Stderr, terminal.Logger)
terminal.Eprintln(res.Error())
os.Exit(res.ExitCode())
}

if args[1] == "pie" {
res := php.Pie("", args[2:], getCliExtraEnv(), os.Stdout, os.Stderr, os.Stderr, terminal.Logger)
terminal.Eprintln(res.Error())
os.Exit(res.ExitCode())
}
}

for _, env := range []string{"BRANCH", "ENV", "APPLICATION_NAME"} {
Expand Down
Loading