<commit_before>package main

import (
	"fmt"
	"os"
	"path"
	"strings"
)

var cmdCreate = &Command{
	UsageLine: "create [appname]",
	Short:     "create an application base on beego framework",
	Long: `
create an application base on beego framework

In the current path, will create a folder named [appname]

In the appname folder has the follow struct:

	|- main.go
	|- conf
	    |-  app.conf
	|- controllers
	     |- default.go
	|- models
	|- static
	     |- js
		 |- css
	     |- img
	|- views
	    index.tpl

`,
}

func init() {
	cmdCreate.Run = createapp
}

func createapp(cmd *Command, args []string) {
	crupath, _ := os.Getwd()
	if len(args) != 1 {
		fmt.Println("error args")
		os.Exit(2)
	}
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		fmt.Println("you should set GOPATH in the env")
		os.Exit(2)
	}
	haspath := false
	if crupath != path.Join(gopath, "src") {
		wgopath := strings.Split(gopath, ";")
		if len(wgopath) >= 1 {
			for _, wg := range wgopath {
				wg = wg + `\src`
				if crupath == wg {
					haspath = true
					break
				}
			}
		}
		if !haspath {
			lgopath := strings.Split(gopath, ":")
			if len(lgopath) >= 1 {
				for _, wg := range lgopath {
					if crupath == path.Join(wg, "src") {
						haspath = true
						break
					}
				}
			}
		}

	} else {
		haspath = true
	}
	if !haspath {
		fmt.Println("can't create application outside of GOPATH")
		fmt.Println("you first should `cd $GOPATH/src` then use create")
		os.Exit(2)
	}
	apppath := path.Join(crupath, args[0])
	os.Mkdir(apppath, 0755)
	fmt.Println("create app folder:", apppath)
	os.Mkdir(path.Join(apppath, "conf"), 0755)
	fmt.Println("create conf:", path.Join(apppath, "conf"))
	os.Mkdir(path.Join(apppath, "controllers"), 0755)
	fmt.Println("create controllers:", path.Join(apppath, "controllers"))
	os.Mkdir(path.Join(apppath, "conf"), 0755)
	fmt.Println("create models:", path.Join(apppath, "models"))
	os.Mkdir(path.Join(apppath, "models"), 0755)
	fmt.Println("create static:", path.Join(apppath, "static"))
	os.Mkdir(path.Join(apppath, "static", "js"), 0755)
	fmt.Println("create static js:", path.Join(apppath, "static", "js"))
	os.Mkdir(path.Join(apppath, "static", "css"), 0755)
	fmt.Println("create static css:", path.Join(apppath, "static", "css"))
	os.Mkdir(path.Join(apppath, "static", "img"), 0755)
	fmt.Println("create static img:", path.Join(apppath, "static", "img"))
	fmt.Println("create views:", path.Join(apppath, "views"))
	os.Mkdir(path.Join(apppath, "views"), 0755)
	fmt.Println("create conf app.conf:", path.Join(apppath, "conf", "app.conf"))
	writetofile(path.Join(apppath, "conf", "app.conf"), "appname = "+args[0])

	fmt.Println("create controllers default.go:", path.Join(apppath, "controllers", "default.go"))
	writetofile(path.Join(apppath, "controllers", "default.go"), controllers)

	fmt.Println("create views index.tpl:", path.Join(apppath, "views", "index.tpl"))
	writetofile(path.Join(apppath, "views", "index.tpl"), indextpl)

	fmt.Println("create main.go:", path.Join(apppath, "main.go"))
	writetofile(path.Join(apppath, "main.go"), strings.Replace(maingo, "{{.Appname}}", args[0], -1))
}

var maingo = `package main

import (
	"{{.Appname}}/controllers"
	"github.com/astaxie/beego"
)

func main() {
	beego.BeeApp.RegisterController("/", &controllers.MainController{})
	beego.BeeApp.Run()
}

`
var controllers = `package controllers

import (
	"github.com/astaxie/beego"
)

type MainController struct {
	beego.Controller
}

func (this *MainController) Get() {
	this.Data["Username"] = "astaxie"
	this.Data["Email"] = "astaxie@gmail.com"
	this.TplNames = "index.tpl"
}
`

var indextpl = `<!DOCTYPE html>

    <title>beego welcome template</title>

Hello, world!{{.Username}},{{.Email}}

`

func writetofile(filename, content string) {
	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	f.WriteString(content)
}
<commit_msg>modify the init code<commit_after>package main

import (
	"fmt"
	"os"
	"path"
	"strings"
)

var cmdCreate = &Command{
	UsageLine: "create [appname]",
	Short:     "create an application base on beego framework",
	Long: `
create an application base on beego framework

In the current path, will create a folder named [appname]

In the appname folder has the follow struct:

	|- main.go
	|- conf
	    |-  app.conf
	|- controllers
	     |- default.go
	|- models
	|- static
	     |- js
		 |- css
	     |- img
	|- views
	    index.tpl

`,
}

func init() {
	cmdCreate.Run = createapp
}

func createapp(cmd *Command, args []string) {
	crupath, _ := os.Getwd()
	if len(args) != 1 {
		fmt.Println("error args")
		os.Exit(2)
	}
	gopath := os.Getenv("GOPATH")
	if gopath == "" {
		fmt.Println("you should set GOPATH in the env")
		os.Exit(2)
	}
	haspath := false
	if crupath != path.Join(gopath, "src") {
		wgopath := strings.Split(gopath, ";")
		if len(wgopath) >= 1 {
			for _, wg := range wgopath {
				wg = wg + `\src`
				if crupath == wg {
					haspath = true
					break
				}
			}
		}
		if !haspath {
			lgopath := strings.Split(gopath, ":")
			if len(lgopath) >= 1 {
				for _, wg := range lgopath {
					if crupath == path.Join(wg, "src") {
						haspath = true
						break
					}
				}
			}
		}

	} else {
		haspath = true
	}
	if !haspath {
		fmt.Println("can't create application outside of GOPATH")
		fmt.Println("you first should `cd $GOPATH/src` then use create")
		os.Exit(2)
	}
	apppath := path.Join(crupath, args[0])
	os.Mkdir(apppath, 0755)
	fmt.Println("create app folder:", apppath)
	os.Mkdir(path.Join(apppath, "conf"), 0755)
	fmt.Println("create conf:", path.Join(apppath, "conf"))
	os.Mkdir(path.Join(apppath, "controllers"), 0755)
	fmt.Println("create controllers:", path.Join(apppath, "controllers"))
	os.Mkdir(path.Join(apppath, "conf"), 0755)
	fmt.Println("create models:", path.Join(apppath, "models"))
	os.Mkdir(path.Join(apppath, "models"), 0755)
	fmt.Println("create static:", path.Join(apppath, "static"))
	os.Mkdir(path.Join(apppath, "static", "js"), 0755)
	fmt.Println("create static js:", path.Join(apppath, "static", "js"))
	os.Mkdir(path.Join(apppath, "static", "css"), 0755)
	fmt.Println("create static css:", path.Join(apppath, "static", "css"))
	os.Mkdir(path.Join(apppath, "static", "img"), 0755)
	fmt.Println("create static img:", path.Join(apppath, "static", "img"))
	fmt.Println("create views:", path.Join(apppath, "views"))
	os.Mkdir(path.Join(apppath, "views"), 0755)
	fmt.Println("create conf app.conf:", path.Join(apppath, "conf", "app.conf"))
	writetofile(path.Join(apppath, "conf", "app.conf"), "appname = "+args[0])

	fmt.Println("create controllers default.go:", path.Join(apppath, "controllers", "default.go"))
	writetofile(path.Join(apppath, "controllers", "default.go"), controllers)

	fmt.Println("create views index.tpl:", path.Join(apppath, "views", "index.tpl"))
	writetofile(path.Join(apppath, "views", "index.tpl"), indextpl)

	fmt.Println("create main.go:", path.Join(apppath, "main.go"))
	writetofile(path.Join(apppath, "main.go"), strings.Replace(maingo, "{{.Appname}}", args[0], -1))
}

var maingo = `package main

import (
	"{{.Appname}}/controllers"
	"github.com/astaxie/beego"
)

func main() {
	beego.RegisterController("/", &controllers.MainController{})
	beego.Run()
}

`
var controllers = `package controllers

import (
	"github.com/astaxie/beego"
)

type MainController struct {
	beego.Controller
}

func (this *MainController) Get() {
	this.Data["Username"] = "astaxie"
	this.Data["Email"] = "astaxie@gmail.com"
	this.TplNames = "index.tpl"
}
`

var indextpl = `<!DOCTYPE html>

    <title>beego welcome template</title>

Hello, world!{{.Username}},{{.Email}}

`

func writetofile(filename, content string) {
	f, err := os.Create(filename)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	f.WriteString(content)
}
<|endoftext|>


<commit_before>package smartcrop

import (
	"fmt"
	"image"
	_ "image/jpeg"
	_ "image/png"
	"os"
	"testing"
)

var (
	testFile = "./samples/test.png"
)

func TestCrop(t *testing.T) {
	fi, _ := os.Open(testFile)
	defer fi.Close()

	img, _, err := image.Decode(fi)
	if err != nil {
		t.Error(err)
	}

	topCrop, scaledImg, err := SmartCrop(&img, 300, 300)
	if err != nil {
		t.Error(err)
	}
	fmt.Printf("Top crop: %+v\n", topCrop)

	cropImage := img.(*image.RGBA).SubImage(image.Rect(topCrop.X, topCrop.Y, topCrop.Width+topCrop.X, topCrop.Height+topCrop.Y))
	WriteImageToJpeg(&cropImage, "/tmp/smartcrop.jpg")
}
<commit_msg>color model independent subimaging<commit_after>package smartcrop

import (
	"errors"
	"fmt"
	"image"
	_ "image/jpeg"
	_ "image/png"
	"os"
	"testing"
)

var (
	testFile = "./samples/test.png"
)

type SubImager interface {
	SubImage(r image.Rectangle) image.Image
}

func TestCrop(t *testing.T) {
	fi, _ := os.Open(testFile)
	defer fi.Close()

	img, _, err := image.Decode(fi)
	if err != nil {
		t.Error(err)
	}

	topCrop, scaledImg, err := SmartCrop(&img, 300, 300)
	if err != nil {
		t.Error(err)
	}
	fmt.Printf("Top crop: %+v\n", topCrop)

	sub, ok := scaledImg.(SubImager)
	if ok {
		cropImage := sub.SubImage(image.Rect(topCrop.X, topCrop.Y, topCrop.Width+topCrop.X, topCrop.Height+topCrop.Y))
		WriteImageToJpeg(&cropImage, "/tmp/smartcrop.jpg")

	} else {
		t.Error(errors.New("No SubImage support"))
	}

}
}
<|endoftext|>


<commit_before>/*

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"flag"
	"os"

	"contrib.go.opencensus.io/exporter/prometheus"
	"contrib.go.opencensus.io/exporter/stackdriver"
	prom "github.com/prometheus/client_golang/prometheus"
	"go.opencensus.io/stats/view"
	corev1 "k8s.io/api/core/v1"

	// Change to use v1 when we only need to support 1.17 and higher kubernetes versions.
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	"k8s.io/apimachinery/pkg/runtime"
	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
	_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"

	// +kubebuilder:scaffold:imports

	api "sigs.k8s.io/multi-tenancy/incubator/hnc/api/v1alpha1"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/forest"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/reconcilers"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/stats"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/validators"
)

var (
	scheme   = runtime.NewScheme()
	setupLog = ctrl.Log.WithName("setup")
)

var (
	metricsAddr          string
	maxReconciles        int
	enableLeaderElection bool
	leaderElectionId     string
	novalidation         bool
	debugLogs            bool
	testLog              bool
	internalCert         bool
	qps                  int
	webhookServerPort    int
)

func init() {
	_ = clientgoscheme.AddToScheme(scheme)

	_ = api.AddToScheme(scheme)
	_ = corev1.AddToScheme(scheme)
	_ = v1beta1.AddToScheme(scheme)
	// +kubebuilder:scaffold:scheme
}

func main() {
	flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
	flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
		"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
	flag.StringVar(&leaderElectionId, "leader-election-id", "controller-leader-election-helper",
		"Leader election id determines the name of the configmap that leader election will use for holding the leader lock.")
	flag.BoolVar(&novalidation, "novalidation", false, "Disables validating webhook")
	flag.BoolVar(&debugLogs, "debug-logs", false, "Shows verbose logs in a human-friendly format.")
	flag.BoolVar(&testLog, "enable-test-log", false, "Enables test log.")
	flag.BoolVar(&internalCert, "enable-internal-cert-management", false, "Enables internal cert management.")
	flag.IntVar(&maxReconciles, "max-reconciles", 1, "Number of concurrent reconciles to perform.")
	flag.IntVar(&qps, "apiserver-qps-throttle", 50, "The maximum QPS to the API server.")
	flag.BoolVar(&stats.SuppressObjectTags, "suppress-object-tags", true, "If true, suppresses the kinds of object metrics to reduce metric cardinality.")
	flag.IntVar(&webhookServerPort, "webhook-server-port", 443, "The port that the webhook server serves at.")
	flag.Parse()

	// Enable OpenCensus exporters to export metrics
	// to Stackdriver Monitoring.
	// Exporters use Application Default Credentials to authenticate.
	// See https://developers.google.com/identity/protocols/application-default-credentials
	// for more details.
	exporter, err := stackdriver.NewExporter(stackdriver.Options{
		// Stackdriver’s minimum stats reporting period must be >= 60 seconds.
		// https://opencensus.io/exporters/supported-exporters/go/stackdriver/
		ReportingInterval: stats.ReportingInterval,
	})
	if err != nil {
		setupLog.Error(err, "cannot create Stackdriver exporter")
		os.Exit(1)
	}
	// Flush must be called before main() exits to ensure metrics are recorded.
	defer exporter.Flush()

	if err := exporter.StartMetricsExporter(); err != nil {
		setupLog.Error(err, "cannot start StackDriver metric exporter")
		os.Exit(1)
	}
	defer exporter.StopMetricsExporter()

	prom.DefaultRegisterer = prom.DefaultRegisterer.(*prom.Registry)
	promExporter, err := prometheus.NewExporter(prometheus.Options{Registry: prom.DefaultRegisterer.(*prom.Registry)})
	view.RegisterExporter(promExporter)

	ctrl.SetLogger(zap.Logger(debugLogs))

	cfg := ctrl.GetConfigOrDie()
	cfg.QPS = float32(qps)
	// By default, Burst is about 2x QPS, but since HNC's "bursts" can last for ~minutes
	// we need to raise the QPS param to be much higher than we ordinarily would. As a
	// result, doubling this higher threshold is probably much too high, so lower it to a more
	// reasonable number.
	//
	// TODO: Better understand the behaviour of Burst, and consider making it equal to QPS if
	// it turns out to be harmful.
	cfg.Burst = int(cfg.QPS * 1.5)

	mgr, err := ctrl.NewManager(cfg, ctrl.Options{
		Scheme:             scheme,
		MetricsBindAddress: metricsAddr,
		LeaderElection:     enableLeaderElection,
		LeaderElectionID:   leaderElectionId,
		Port:               webhookServerPort,
	})
	if err != nil {
		setupLog.Error(err, "unable to start manager")
		os.Exit(1)
	}

	// Make sure certs are generated and valid if webhooks are enabled and internal certs are used.
	setupFinished, err := validators.CreateCertsIfNeeded(mgr, novalidation, internalCert)
	if err != nil {
		setupLog.Error(err, "unable to set up cert rotation")
		os.Exit(1)
	}

	go startControllers(mgr, setupFinished)

	setupLog.Info("starting manager")
	if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
		setupLog.Error(err, "problem running manager")
		os.Exit(1)
	}
}

func startControllers(mgr ctrl.Manager, setupFinished chan struct{}) {
	// Block until the setup finishes.
	<-setupFinished

	if testLog {
		stats.StartLoggingActivity()
	}

	// Create all reconciling controllers
	f := forest.NewForest()
	setupLog.Info("Creating controllers", "maxReconciles", maxReconciles)
	if err := reconcilers.Create(mgr, f, maxReconciles); err != nil {
		setupLog.Error(err, "cannot create controllers")
		os.Exit(1)
	}

	// Create all validating admission controllers.
	if !novalidation {
		setupLog.Info("Registering validating webhook (won't work when running locally; use --novalidation)")
		validators.Create(mgr, f)
	}
}
<commit_msg>Make Stackdriver optional and fix startup logs<commit_after>/*

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package main

import (
	"flag"
	"os"

	"contrib.go.opencensus.io/exporter/prometheus"
	"contrib.go.opencensus.io/exporter/stackdriver"
	prom "github.com/prometheus/client_golang/prometheus"
	"go.opencensus.io/stats/view"
	corev1 "k8s.io/api/core/v1"

	// Change to use v1 when we only need to support 1.17 and higher kubernetes versions.
	"k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
	"k8s.io/apimachinery/pkg/runtime"
	clientgoscheme "k8s.io/client-go/kubernetes/scheme"
	_ "k8s.io/client-go/plugin/pkg/client/auth/gcp"
	ctrl "sigs.k8s.io/controller-runtime"
	"sigs.k8s.io/controller-runtime/pkg/log/zap"

	// +kubebuilder:scaffold:imports

	api "sigs.k8s.io/multi-tenancy/incubator/hnc/api/v1alpha1"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/forest"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/reconcilers"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/stats"
	"sigs.k8s.io/multi-tenancy/incubator/hnc/internal/validators"
)

var (
	scheme   = runtime.NewScheme()
	setupLog = zap.New().WithName("setup")
)

var (
	metricsAddr          string
	maxReconciles        int
	enableLeaderElection bool
	leaderElectionId     string
	novalidation         bool
	debugLogs            bool
	testLog              bool
	internalCert         bool
	qps                  int
	webhookServerPort    int
)

func init() {
	setupLog.Info("Starting main.go:init()")
	defer setupLog.Info("Finished main.go:init()")
	_ = clientgoscheme.AddToScheme(scheme)

	_ = api.AddToScheme(scheme)
	_ = corev1.AddToScheme(scheme)
	_ = v1beta1.AddToScheme(scheme)
	// +kubebuilder:scaffold:scheme
}

func main() {
	setupLog.Info("Parsing flags")
	flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
	flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
		"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.")
	flag.StringVar(&leaderElectionId, "leader-election-id", "controller-leader-election-helper",
		"Leader election id determines the name of the configmap that leader election will use for holding the leader lock.")
	flag.BoolVar(&novalidation, "novalidation", false, "Disables validating webhook")
	flag.BoolVar(&debugLogs, "debug-logs", false, "Shows verbose logs in a human-friendly format.")
	flag.BoolVar(&testLog, "enable-test-log", false, "Enables test log.")
	flag.BoolVar(&internalCert, "enable-internal-cert-management", false, "Enables internal cert management.")
	flag.IntVar(&maxReconciles, "max-reconciles", 1, "Number of concurrent reconciles to perform.")
	flag.IntVar(&qps, "apiserver-qps-throttle", 50, "The maximum QPS to the API server.")
	flag.BoolVar(&stats.SuppressObjectTags, "suppress-object-tags", true, "If true, suppresses the kinds of object metrics to reduce metric cardinality.")
	flag.IntVar(&webhookServerPort, "webhook-server-port", 443, "The port that the webhook server serves at.")
	flag.Parse()

	// Enable OpenCensus exporters to export metrics
	// to Stackdriver Monitoring.
	// Exporters use Application Default Credentials to authenticate.
	// See https://developers.google.com/identity/protocols/application-default-credentials
	// for more details.
	setupLog.Info("Creating OpenCensus->Stackdriver exporter")
	sd, err := stackdriver.NewExporter(stackdriver.Options{
		// Stackdriver’s minimum stats reporting period must be >= 60 seconds.
		// https://opencensus.io/exporters/supported-exporters/go/stackdriver/
		ReportingInterval: stats.ReportingInterval,
	})
	if err == nil {
		// Flush must be called before main() exits to ensure metrics are recorded.
		defer sd.Flush()
		err = sd.StartMetricsExporter()
		if err == nil {
			defer sd.StopMetricsExporter()
		}
	}
	if err != nil {
		setupLog.Error(err, "cannot create Stackdriver exporter")
	}

	setupLog.Info("Creating Prometheus exporter")
	prom.DefaultRegisterer = prom.DefaultRegisterer.(*prom.Registry)
	promExporter, err := prometheus.NewExporter(prometheus.Options{Registry: prom.DefaultRegisterer.(*prom.Registry)})
	if err != nil {
		setupLog.Error(err, "Cannot create Prometheus exporter")
	}
	view.RegisterExporter(promExporter)

	setupLog.Info("Configuring controller-manager")
	ctrl.SetLogger(zap.Logger(debugLogs))
	cfg := ctrl.GetConfigOrDie()
	cfg.QPS = float32(qps)
	// By default, Burst is about 2x QPS, but since HNC's "bursts" can last for ~minutes
	// we need to raise the QPS param to be much higher than we ordinarily would. As a
	// result, doubling this higher threshold is probably much too high, so lower it to a more
	// reasonable number.
	//
	// TODO: Better understand the behaviour of Burst, and consider making it equal to QPS if
	// it turns out to be harmful.
	cfg.Burst = int(cfg.QPS * 1.5)
	mgr, err := ctrl.NewManager(cfg, ctrl.Options{
		Scheme:             scheme,
		MetricsBindAddress: metricsAddr,
		LeaderElection:     enableLeaderElection,
		LeaderElectionID:   leaderElectionId,
		Port:               webhookServerPort,
	})
	if err != nil {
		setupLog.Error(err, "unable to start manager")
		os.Exit(1)
	}

	// Make sure certs are generated and valid if webhooks are enabled and internal certs are used.
	setupLog.Info("Starting certificate generation")
	setupFinished, err := validators.CreateCertsIfNeeded(mgr, novalidation, internalCert)
	if err != nil {
		setupLog.Error(err, "unable to set up cert rotation")
		os.Exit(1)
	}

	go startControllers(mgr, setupFinished)

	setupLog.Info("Starting manager")
	if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
		setupLog.Error(err, "problem running manager")
		os.Exit(1)
	}
}

func startControllers(mgr ctrl.Manager, setupFinished chan struct{}) {
	setupLog.Info("Waiting for certificate generation to complete")
	// Block until the setup finishes.
	<-setupFinished

	if testLog {
		stats.StartLoggingActivity()
	}

	// Create all reconciling controllers
	f := forest.NewForest()
	setupLog.Info("Creating controllers", "maxReconciles", maxReconciles)
	if err := reconcilers.Create(mgr, f, maxReconciles); err != nil {
		setupLog.Error(err, "cannot create controllers")
		os.Exit(1)
	}

	// Create all validating admission controllers.
	if !novalidation {
		setupLog.Info("Registering validating webhook (won't work when running locally; use --novalidation)")
		validators.Create(mgr, f)
	}

	setupLog.Info("All controllers started; setup complete")
}
<|endoftext|>


<commit_before>package chain

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

var (
	b0   = "0"
	b1   = "1"
	bEnd = "_END_"
)

func Example() {
	// Each nested handler writes either "0", or "1", to the response
	// body before and after ServeHTTPContext() is called.
	//
	// endHandler writes "_END_" to the response body and returns.

	ch00 := New(nestedHandler0, nestedHandler0)
	ch001 := ch00.Append(nestedHandler1)

	ch1 := New(nestedHandler1)
	ch1001 := ch1.Merge(ch001)

	mux := http.NewServeMux()
	mux.Handle("/00_End", ch00.EndFn(endHandler))
	mux.Handle("/001_End", ch001.EndFn(endHandler))
	mux.Handle("/1001_End", ch1001.EndFn(endHandler))

	server := httptest.NewServer(mux)

	resp0, err := getRespBody(server.URL + "/00_End")
	if err != nil {
		fmt.Println(err)
	}

	resp1, err := getRespBody(server.URL + "/001_End")
	if err != nil {
		fmt.Println(err)
	}

	resp2, err := getRespBody(server.URL + "/1001_End")
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Chain 00 Resp:", resp0)
	fmt.Println("Chain 001 Resp:", resp1)
	fmt.Println("Chain 1001 Resp:", resp2)

	// Output:
	// Chain 00 Resp: 00_END_00
	// Chain 001 Resp: 001_END_100
	// Chain 1001 Resp: 1001_END_1001
}

func TestNew(t *testing.T) {
	c := New(emptyNestedHandler)
	if c.hs == nil {
		t.Fatal("want new chain with hs set, got nil")
	}
}

func TestAppend(t *testing.T) {
	c := New(emptyNestedHandler)
	c = c.Append(emptyNestedHandler)
	if len(c.hs) != 2 {
		t.Fatalf("want chain hs with len 2, got %d\n", len(c.hs))
	}
}

func getRespBody(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	_ = resp.Body.Close()

	return string(body), nil
}

func getRespStatus(url string) (int, error) {
	resp, err := http.Get(url)
	if err != nil {
		return 0, err
	}

	_ = resp.Body.Close()

	return resp.StatusCode, nil
}

func nestedHandler0(n http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(b0))
		n.ServeHTTP(w, r)
		_, _ = w.Write([]byte(b0))
	})
}

func nestedHandler1(n http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(b1))
		n.ServeHTTP(w, r)
		_, _ = w.Write([]byte(b1))
	})
}

func emptyNestedHandler(n http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		n.ServeHTTP(w, r)
	})
}

func endHandler(w http.ResponseWriter, r *http.Request) {
	_, _ = w.Write([]byte(bEnd))
}

func BenchmarkChain10(b *testing.B) {
	c0 := New(emptyNestedHandler,
		emptyNestedHandler, emptyNestedHandler, emptyNestedHandler,
		emptyNestedHandler, emptyNestedHandler, emptyNestedHandler,
		emptyNestedHandler, emptyNestedHandler, emptyNestedHandler)

	m := http.NewServeMux()
	m.Handle("/", c0.EndFn(nilHandler))

	s := httptest.NewServer(m)

	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		resp, err := http.Get(s.URL + "/")
		if err != nil {
			b.Error(err)
		}

		_ = resp.Body.Close()
	}
}

func BenchmarkNest10(b *testing.B) {
	h := emptyNestedHandler(emptyNestedHandler(
		emptyNestedHandler(emptyNestedHandler(
			emptyNestedHandler(emptyNestedHandler(
				emptyNestedHandler(emptyNestedHandler(
					emptyNestedHandler(emptyNestedHandler(
						http.HandlerFunc(nilHandler)))))))))))

	m := http.NewServeMux()
	m.Handle("/", h)

	s := httptest.NewServer(m)

	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		resp, err := http.Get(s.URL + "/")
		if err != nil {
			b.Error(err)
		}

		_ = resp.Body.Close()
	}
}
<commit_msg>Add test for merge.<commit_after>package chain

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/http/httptest"
	"testing"
)

var (
	b0   = "0"
	b1   = "1"
	bEnd = "_END_"
)

func Example() {
	// Each nested handler writes either "0", or "1", to the response
	// body before and after ServeHTTPContext() is called.
	//
	// endHandler writes "_END_" to the response body and returns.

	ch00 := New(nestedHandler0, nestedHandler0)
	ch001 := ch00.Append(nestedHandler1)

	ch1 := New(nestedHandler1)
	ch1001 := ch1.Merge(ch001)

	mux := http.NewServeMux()
	mux.Handle("/00_End", ch00.EndFn(endHandler))
	mux.Handle("/001_End", ch001.EndFn(endHandler))
	mux.Handle("/1001_End", ch1001.EndFn(endHandler))

	server := httptest.NewServer(mux)

	resp0, err := getRespBody(server.URL + "/00_End")
	if err != nil {
		fmt.Println(err)
	}

	resp1, err := getRespBody(server.URL + "/001_End")
	if err != nil {
		fmt.Println(err)
	}

	resp2, err := getRespBody(server.URL + "/1001_End")
	if err != nil {
		fmt.Println(err)
	}

	fmt.Println("Chain 00 Resp:", resp0)
	fmt.Println("Chain 001 Resp:", resp1)
	fmt.Println("Chain 1001 Resp:", resp2)

	// Output:
	// Chain 00 Resp: 00_END_00
	// Chain 001 Resp: 001_END_100
	// Chain 1001 Resp: 1001_END_1001
}

func TestNew(t *testing.T) {
	c := New(emptyNestedHandler)
	if c.hs == nil {
		t.Fatal("want new chain with hs set, got nil")
	}
}

func TestAppend(t *testing.T) {
	c := New(emptyNestedHandler)
	c = c.Append(emptyNestedHandler)
	if len(c.hs) != 2 {
		t.Fatalf("want chain hs with len 2, got %d\n", len(c.hs))
	}
}

func TestMerge(t *testing.T) {
	c1 := New(emptyNestedHandler)
	c2 := New(emptyNestedHandler, emptyNestedHandler)
	c3 := c1.Merge(c2)
	if len(c3.hs) != 3 {
		t.Fatalf("want chain hs with len 3, go %d\n", len(c3.hs))
	}
}

func getRespBody(url string) (string, error) {
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	_ = resp.Body.Close()

	return string(body), nil
}

func getRespStatus(url string) (int, error) {
	resp, err := http.Get(url)
	if err != nil {
		return 0, err
	}

	_ = resp.Body.Close()

	return resp.StatusCode, nil
}

func nestedHandler0(n http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(b0))
		n.ServeHTTP(w, r)
		_, _ = w.Write([]byte(b0))
	})
}

func nestedHandler1(n http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte(b1))
		n.ServeHTTP(w, r)
		_, _ = w.Write([]byte(b1))
	})
}

func emptyNestedHandler(n http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		n.ServeHTTP(w, r)
	})
}

func endHandler(w http.ResponseWriter, r *http.Request) {
	_, _ = w.Write([]byte(bEnd))
}

func BenchmarkChain10(b *testing.B) {
	c0 := New(emptyNestedHandler,
		emptyNestedHandler, emptyNestedHandler, emptyNestedHandler,
		emptyNestedHandler, emptyNestedHandler, emptyNestedHandler,
		emptyNestedHandler, emptyNestedHandler, emptyNestedHandler)

	m := http.NewServeMux()
	m.Handle("/", c0.EndFn(nilHandler))

	s := httptest.NewServer(m)

	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		resp, err := http.Get(s.URL + "/")
		if err != nil {
			b.Error(err)
		}

		_ = resp.Body.Close()
	}
}

func BenchmarkNest10(b *testing.B) {
	h := emptyNestedHandler(emptyNestedHandler(
		emptyNestedHandler(emptyNestedHandler(
			emptyNestedHandler(emptyNestedHandler(
				emptyNestedHandler(emptyNestedHandler(
					emptyNestedHandler(emptyNestedHandler(
						http.HandlerFunc(nilHandler)))))))))))

	m := http.NewServeMux()
	m.Handle("/", h)

	s := httptest.NewServer(m)

	b.ResetTimer()

	for n := 0; n < b.N; n++ {
		resp, err := http.Get(s.URL + "/")
		if err != nil {
			b.Error(err)
		}

		_ = resp.Body.Close()
	}
}
<|endoftext|>


<commit_before>package mci

import (
	"encoding/json"
	"errors"
	"github.com/cloudfoundry-community/gautocloud"
	"github.com/cloudfoundry-community/gautocloud/loader"
	"github.com/cloudfoundry-community/gautocloud/logger"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

func PushConfig(mattermostConfig *MattermostConfig, configFilePath string) error {
	var currentConfig map[string]interface{}
	configData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return err
	}
	err = json.Unmarshal(configData, &currentConfig)
	if err != nil {
		return err
	}

	var newConfig map[string]interface{}
	configData, err = json.Marshal(mattermostConfig)
	if err != nil {
		return nil
	}
	err = json.Unmarshal(configData, &newConfig)
	if err != nil {
		return err
	}

	finalConfig := mergeMaps(currentConfig, newConfig)

	configData, err = json.Marshal(finalConfig)
	if err != nil {
		return nil
	}
	ioutil.WriteFile(configFilePath, configData, 0644)
	return nil
}
func mergeMaps(parent, partial map[string]interface{}) map[string]interface{} {
	for k, v := range partial {
		if _, ok := parent[k]; !ok {
			parent[k] = v
			continue
		}
		if vMap, ok := v.(map[string]interface{}); ok {
			parent[k] = mergeMaps(parent[k].(map[string]interface{}), vMap)
			continue
		}
		parent[k] = v
	}
	return parent
}

func CloudifyConfig(mattermostConfig *MattermostConfig) error {
	ld := loader.NewLoaderWithLogger(
		gautocloud.CloudEnvs(),
		log.New(os.Stdout, "", log.Ldate|log.Ltime),
		logger.Linfo,
	)
	var err error
	if !ld.IsInACloudEnv() {
		return errors.New("Not in any cloud environment.")
	}
	mattermostConfig.ServiceSettings.ListenAddress = ":" + os.Getenv("PORT")
	if err != nil {
		return err
	}
	if mattermostConfig.ServiceSettings.WebsocketPort == 0 {
		mattermostConfig.ServiceSettings.WebsocketPort = 80
	}
	if mattermostConfig.ServiceSettings.WebsocketSecurePort == 0 {
		mattermostConfig.ServiceSettings.WebsocketSecurePort = 443
	}
	err = cloudifyDatabase(ld, mattermostConfig)
	if err != nil {
		return err
	}
	err = cloudifySmtp(ld, mattermostConfig)
	if err != nil && !strings.Contains(err.Error(), "cannot be found") {
		return err
	}
	err = cloudifyS3(ld, mattermostConfig)
	if err != nil && !strings.Contains(err.Error(), "cannot be found") {
		return err
	}
	return nil
}

func ExtractConfig(configFilePath string) (*MattermostConfig, error) {
	var err error
	var mattermostConfig MattermostConfig
	configData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(configData, &mattermostConfig)
	if err != nil {
		return nil, err
	}
	return &mattermostConfig, nil
}
<commit_msg>set site url automatically<commit_after>package mci

import (
	"encoding/json"
	"errors"
	"github.com/cloudfoundry-community/gautocloud"
	"github.com/cloudfoundry-community/gautocloud/loader"
	"github.com/cloudfoundry-community/gautocloud/logger"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

func PushConfig(mattermostConfig *MattermostConfig, configFilePath string) error {
	var currentConfig map[string]interface{}
	configData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return err
	}
	err = json.Unmarshal(configData, &currentConfig)
	if err != nil {
		return err
	}

	var newConfig map[string]interface{}
	configData, err = json.Marshal(mattermostConfig)
	if err != nil {
		return nil
	}
	err = json.Unmarshal(configData, &newConfig)
	if err != nil {
		return err
	}

	finalConfig := mergeMaps(currentConfig, newConfig)

	configData, err = json.Marshal(finalConfig)
	if err != nil {
		return nil
	}
	ioutil.WriteFile(configFilePath, configData, 0644)
	return nil
}
func mergeMaps(parent, partial map[string]interface{}) map[string]interface{} {
	for k, v := range partial {
		if _, ok := parent[k]; !ok {
			parent[k] = v
			continue
		}
		if vMap, ok := v.(map[string]interface{}); ok {
			parent[k] = mergeMaps(parent[k].(map[string]interface{}), vMap)
			continue
		}
		parent[k] = v
	}
	return parent
}

func CloudifyConfig(mattermostConfig *MattermostConfig) error {
	ld := loader.NewLoaderWithLogger(
		gautocloud.CloudEnvs(),
		log.New(os.Stdout, "", log.Ldate|log.Ltime),
		logger.Linfo,
	)

	var err error
	if !ld.IsInACloudEnv() {
		return errors.New("Not in any cloud environment.")
	}
	mattermostConfig.ServiceSettings.ListenAddress = ":" + os.Getenv("PORT")
	if err != nil {
		return err
	}
	if mattermostConfig.ServiceSettings.WebsocketPort == 0 {
		mattermostConfig.ServiceSettings.WebsocketPort = 80
	}
	if mattermostConfig.ServiceSettings.WebsocketSecurePort == 0 {
		mattermostConfig.ServiceSettings.WebsocketSecurePort = 443
	}
	mattermostConfig.ServiceSettings.SiteURL = RetrieveSiteUrl(ld)
	err = cloudifyDatabase(ld, mattermostConfig)
	if err != nil {
		return err
	}
	err = cloudifySmtp(ld, mattermostConfig)
	if err != nil && !strings.Contains(err.Error(), "cannot be found") {
		return err
	}
	err = cloudifyS3(ld, mattermostConfig)
	if err != nil && !strings.Contains(err.Error(), "cannot be found") {
		return err
	}
	return nil
}
func RetrieveSiteUrl(ld *loader.Loader) string {
	cloudProps := ld.CurrentCloudEnv().GetAppInfo().Properties
	if _, ok := cloudProps["uris"]; !ok {
		return ""
	}
	if uris, ok := cloudProps["uris"].([]string); ok {
		return "http://" + uris[0]
	}
	return ""
}
func ExtractConfig(configFilePath string) (*MattermostConfig, error) {
	var err error
	var mattermostConfig MattermostConfig
	configData, err := ioutil.ReadFile(configFilePath)
	if err != nil {
		return nil, err
	}
	err = json.Unmarshal(configData, &mattermostConfig)
	if err != nil {
		return nil, err
	}
	return &mattermostConfig, nil
}
<|endoftext|>


<commit_before>package common

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"os"
	"strings"

	"github.com/hashicorp/terraform-plugin-sdk/v2/meta"
	"github.com/manicminer/hamilton/auth"
	"github.com/manicminer/hamilton/environments"
	"github.com/manicminer/hamilton/msgraph"

	"github.com/hashicorp/terraform-provider-azuread/version"
)

type ClientOptions struct {
	Environment environments.Environment
	TenantID    string

	PartnerID        string
	TerraformVersion string

	Authorizer auth.Authorizer
}

func (o ClientOptions) ConfigureClient(c *msgraph.Client) {
	c.Authorizer = o.Authorizer
	c.Endpoint = o.Environment.MsGraph.Endpoint
	c.UserAgent = o.userAgent(c.UserAgent)

	if c.RequestMiddlewares == nil {
		c.RequestMiddlewares = &[]msgraph.RequestMiddleware{}
	}
	if c.ResponseMiddlewares == nil {
		c.ResponseMiddlewares = &[]msgraph.ResponseMiddleware{}
	}
	*c.RequestMiddlewares = append(*c.RequestMiddlewares, o.requestLogger)
	*c.ResponseMiddlewares = append(*c.ResponseMiddlewares, o.responseLogger)

	// Default retry limit, can be overridden from within a resource
	c.RetryableClient.RetryMax = 8
}

func (o ClientOptions) requestLogger(req *http.Request) (*http.Request, error) {
	if req == nil {
		return nil, nil
	}

	// Don't log the Authorization header
	authHeaderName := "Authorization"
	authHeaderValue := req.Header.Get(authHeaderName)
	if authHeaderValue != "" {
		req.Header.Del(authHeaderName)
	}

	if dump, err := httputil.DumpRequestOut(req, true); err == nil {
		log.Printf("[DEBUG] Begin AzureAD Request: ==========================================\n%s\n========================================= End AzureAD Request\n", dump)
	} else {
		// fallback to basic message
		log.Printf("[DEBUG] AzureAD Request: %s %s\n", req.Method, req.URL)
	}

	if authHeaderValue != "" {
		req.Header.Add(authHeaderName, authHeaderValue)
	}
	return req, nil
}

func (o ClientOptions) responseLogger(req *http.Request, resp *http.Response) (*http.Response, error) {
	if resp != nil {
		if dump, err2 := httputil.DumpResponse(resp, true); err2 == nil {
			log.Printf("[DEBUG] Begin AzureAD Response for %s %s: ==========================================\n%s\n========================================== End AzureAD Response\n", req.Method, req.URL, dump)
		} else {
			log.Printf("[DEBUG] AzureAD Response: %s for %s %s\n", resp.Status, req.Method, req.URL)
		}
	} else {
		log.Printf("[DEBUG] AzureAD Request for %s %s completed with no response", req.Method, req.URL)
	}
	return resp, nil
}

func (o ClientOptions) userAgent(sdkUserAgent string) (userAgent string) {
	tfUserAgent := fmt.Sprintf("HashiCorp Terraform/%s (+https://www.terraform.io) Terraform Plugin SDK/%s", o.TerraformVersion, meta.SDKVersionString())
	providerUserAgent := fmt.Sprintf("%s terraform-provider-azuread/%s", tfUserAgent, version.ProviderVersion)
	userAgent = strings.TrimSpace(fmt.Sprintf("%s %s", providerUserAgent, sdkUserAgent))

	// append the CloudShell version to the user agent if it exists
	if azureAgent := os.Getenv("AZURE_HTTP_USER_AGENT"); azureAgent != "" {
		userAgent = fmt.Sprintf("%s %s", userAgent, azureAgent)
	}

	if o.PartnerID != "" {
		userAgent = fmt.Sprintf("%s pid-%s", userAgent, o.PartnerID)
	}

	return
}
<commit_msg>Generate a UUID for requests to correlate requests and responses in logs<commit_after>package common

import (
	"context"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"os"
	"strings"

	"github.com/hashicorp/go-uuid"
	"github.com/hashicorp/terraform-plugin-sdk/v2/meta"
	"github.com/manicminer/hamilton/auth"
	"github.com/manicminer/hamilton/environments"
	"github.com/manicminer/hamilton/msgraph"

	"github.com/hashicorp/terraform-provider-azuread/version"
)

type contextKey string

type ClientOptions struct {
	Environment environments.Environment
	TenantID    string

	PartnerID        string
	TerraformVersion string

	Authorizer auth.Authorizer
}

func (o ClientOptions) ConfigureClient(c *msgraph.Client) {
	c.Authorizer = o.Authorizer
	c.Endpoint = o.Environment.MsGraph.Endpoint
	c.UserAgent = o.userAgent(c.UserAgent)

	if c.RequestMiddlewares == nil {
		c.RequestMiddlewares = &[]msgraph.RequestMiddleware{}
	}
	if c.ResponseMiddlewares == nil {
		c.ResponseMiddlewares = &[]msgraph.ResponseMiddleware{}
	}
	*c.RequestMiddlewares = append(*c.RequestMiddlewares, o.requestLogger)
	*c.ResponseMiddlewares = append(*c.ResponseMiddlewares, o.responseLogger)

	// Default retry limit, can be overridden from within a resource
	c.RetryableClient.RetryMax = 8
}

func (o ClientOptions) requestLogger(req *http.Request) (*http.Request, error) {
	if req == nil {
		return nil, nil
	}

	requestId, err := uuid.GenerateUUID()
	if err != nil {
		return nil, err
	}

	ctx := req.Context()
	newReq := req.WithContext(context.WithValue(ctx, contextKey("requestId"), requestId))

	// Don't log the Authorization header
	authHeaderName := "Authorization"
	authHeaderValue := newReq.Header.Get(authHeaderName)
	if authHeaderValue != "" {
		newReq.Header.Del(authHeaderName)
	}

	if dump, err := httputil.DumpRequestOut(newReq, true); err == nil {
		log.Printf(`[DEBUG] ============================ Begin AzureAD Request ============================
Request ID: %s

%s
============================= End AzureAD Request =============================
`, requestId, dump)
	} else {
		// fallback to basic message
		log.Printf("[DEBUG] AzureAD Request %s: %s %s\n", requestId, newReq.Method, newReq.URL)
	}

	if authHeaderValue != "" {
		newReq.Header.Add(authHeaderName, authHeaderValue)
	}
	return newReq, nil
}

func (o ClientOptions) responseLogger(req *http.Request, resp *http.Response) (*http.Response, error) {
	requestId := "UNKNOWN"

	if req != nil {
		if v := req.Context().Value(contextKey("requestId")); v != nil {
			requestId = v.(string)
		}
	}

	if resp != nil {
		if dump, err2 := httputil.DumpResponse(resp, true); err2 == nil {
			log.Printf(`[DEBUG] ============================ Begin AzureAD Response ===========================
%s %s
Request ID: %s

%s
============================= End AzureAD Response ============================
`, req.Method, req.URL, requestId, dump)
		} else {
			log.Printf("[DEBUG] AzureAD Response: %s for %s (%s %s)\n", resp.Status, requestId, req.Method, req.URL)
		}
	} else {
		log.Printf("[DEBUG] AzureAD Request for %s (%s %s) completed with no response", requestId, req.Method, req.URL)
	}

	return resp, nil
}

func (o ClientOptions) userAgent(sdkUserAgent string) (userAgent string) {
	tfUserAgent := fmt.Sprintf("HashiCorp Terraform/%s (+https://www.terraform.io) Terraform Plugin SDK/%s", o.TerraformVersion, meta.SDKVersionString())
	providerUserAgent := fmt.Sprintf("%s terraform-provider-azuread/%s", tfUserAgent, version.ProviderVersion)
	userAgent = strings.TrimSpace(fmt.Sprintf("%s %s", providerUserAgent, sdkUserAgent))

	// append the CloudShell version to the user agent if it exists
	if azureAgent := os.Getenv("AZURE_HTTP_USER_AGENT"); azureAgent != "" {
		userAgent = fmt.Sprintf("%s %s", userAgent, azureAgent)
	}

	if o.PartnerID != "" {
		userAgent = fmt.Sprintf("%s pid-%s", userAgent, o.PartnerID)
	}

	return
}
<|endoftext|>


<commit_before>package telebot

import (
	"time"
)

// Message object represents a message.
type Message struct {
	ID       int  `json:"message_id"`
	Sender   User `json:"from"`
	Unixtime int  `json:"date"`

	// For forwarded messages, sender of the original message.
	OriginalSender User `json:"forward_from"`

	// For forwarded messages, unixtime of the original message.
	OriginalUnixtime int `json:"forward_date"`

	// For replies, ReplyTo represents the original message.
	// Note that the Message object in this field will not
	// contain further ReplyTo fields even if it
	// itself is a reply.
	ReplyTo *Message `json:"reply_to_message"`

	// For a text message, the actual UTF-8 text of the message
	Text string `json:"text"`

	// For an audio recording, information about it.
	Audio Audio `json:"audio"`

	// For a general file, information about it.
	Document Document `json:"document"`

	// For a photo, available thumbnails.
	Photo []Thumbnail `json:"photo"`

	// For a sticker, information about it.
	Sticker Sticker `json:"sticker"`

	// For a video, information about it.
	Video Video `json:"video"`

	// For a contact, contact information itself.
	Contact Contact `json:"contact"`

	// For a location, its longitude and latitude.
	Location Location `json:"location"`

	// A group chat message belongs to, empty if personal.
	Chat User `json:"chat"`

	// For a service message, represents a user,
	// that just got added to chat, this message came from.
	//
	// Sender leads to User, capable of invite.
	//
	// UserJoined might be the Bot itself.
	UserJoined User `json:"new_chat_participant"`

	// For a service message, represents a user,
	// that just left chat, this message came from.
	//
	// If user was kicked, Sender leads to a User,
	// capable of this kick.
	//
	// UserLeft might be the Bot itself.
	UserLeft User `json:"left_chat_participant"`

	// For a service message, represents a new title
	// for chat this message came from.
	//
	// Sender would lead to a User, capable of change.
	NewChatTitle string `json:"new_chat_title"`

	// For a service message, represents all available
	// thumbnails of new chat photo.
	//
	// Sender would lead to a User, capable of change.
	NewChatPhoto []Thumbnail `json:"new_chat_photo"`

	// For a service message, true if chat photo just
	// got removed.
	//
	// Sender would lead to a User, capable of change.
	ChatPhotoDeleted bool `json:"delete_chat_photo"`

	// For a service message, true if group has been created.
	//
	// You would recieve such a message if you are one of
	// initial group chat members.
	//
	// Sender would lead to creator of the chat.
	ChatCreated bool `json:"group_chat_created"`
}

// Origin returns an origin of message: group chat / personal.
func (m Message) Origin() User {
	if (m.Chat != User{}) {
		return m.Chat
	}

	return m.Sender
}

// Time returns the moment of message creation in local time.
func (m Message) Time() time.Time {
	return time.Unix(int64(m.Unixtime), 0)
}

// IsForwarded says whether message is forwarded copy of another
// message or not.
func (m Message) IsForwarded() bool {
	return m.OriginalSender != User{}
}

// IsReply says whether message is reply to another message or not.
func (m Message) IsReply() bool {
	return m.ReplyTo != nil
}

// IsPersonal returns true, if message is a personal message,
// returns false if sent to group chat.
func (m Message) IsPersonal() bool {
	return m.Chat != User{}
}

// IsService returns true, if message is a service message,
// returns false otherwise.
//
// Service messages are automatically sent messages, which
// typically occur on some global action. For instance, when
// anyone leaves the chat or chat title changes.
func (m Message) IsService() bool {
	service := false

	if (m.UserJoined != User{}) {
		service = true
	}

	if (m.UserLeft != User{}) {
		service = true
	}

	if m.NewChatTitle != "" {
		service = true
	}

	if len(m.NewChatPhoto) > 0 {
		service = true
	}

	if m.ChatPhotoDeleted {
		service = true
	}

	if m.ChatCreated {
		service = true
	}

	return service
}
<commit_msg>DRY condition fix<commit_after>package telebot

import (
	"time"
)

// Message object represents a message.
type Message struct {
	ID       int  `json:"message_id"`
	Sender   User `json:"from"`
	Unixtime int  `json:"date"`

	// For forwarded messages, sender of the original message.
	OriginalSender User `json:"forward_from"`

	// For forwarded messages, unixtime of the original message.
	OriginalUnixtime int `json:"forward_date"`

	// For replies, ReplyTo represents the original message.
	// Note that the Message object in this field will not
	// contain further ReplyTo fields even if it
	// itself is a reply.
	ReplyTo *Message `json:"reply_to_message"`

	// For a text message, the actual UTF-8 text of the message
	Text string `json:"text"`

	// For an audio recording, information about it.
	Audio Audio `json:"audio"`

	// For a general file, information about it.
	Document Document `json:"document"`

	// For a photo, available thumbnails.
	Photo []Thumbnail `json:"photo"`

	// For a sticker, information about it.
	Sticker Sticker `json:"sticker"`

	// For a video, information about it.
	Video Video `json:"video"`

	// For a contact, contact information itself.
	Contact Contact `json:"contact"`

	// For a location, its longitude and latitude.
	Location Location `json:"location"`

	// A group chat message belongs to, empty if personal.
	Chat User `json:"chat"`

	// For a service message, represents a user,
	// that just got added to chat, this message came from.
	//
	// Sender leads to User, capable of invite.
	//
	// UserJoined might be the Bot itself.
	UserJoined User `json:"new_chat_participant"`

	// For a service message, represents a user,
	// that just left chat, this message came from.
	//
	// If user was kicked, Sender leads to a User,
	// capable of this kick.
	//
	// UserLeft might be the Bot itself.
	UserLeft User `json:"left_chat_participant"`

	// For a service message, represents a new title
	// for chat this message came from.
	//
	// Sender would lead to a User, capable of change.
	NewChatTitle string `json:"new_chat_title"`

	// For a service message, represents all available
	// thumbnails of new chat photo.
	//
	// Sender would lead to a User, capable of change.
	NewChatPhoto []Thumbnail `json:"new_chat_photo"`

	// For a service message, true if chat photo just
	// got removed.
	//
	// Sender would lead to a User, capable of change.
	ChatPhotoDeleted bool `json:"delete_chat_photo"`

	// For a service message, true if group has been created.
	//
	// You would recieve such a message if you are one of
	// initial group chat members.
	//
	// Sender would lead to creator of the chat.
	ChatCreated bool `json:"group_chat_created"`
}

// Origin returns an origin of message: group chat / personal.
func (m Message) Origin() User {
	if m.IsPersonal() {
		return m.Chat
	}

	return m.Sender
}

// Time returns the moment of message creation in local time.
func (m Message) Time() time.Time {
	return time.Unix(int64(m.Unixtime), 0)
}

// IsForwarded says whether message is forwarded copy of another
// message or not.
func (m Message) IsForwarded() bool {
	return m.OriginalSender != User{}
}

// IsReply says whether message is reply to another message or not.
func (m Message) IsReply() bool {
	return m.ReplyTo != nil
}

// IsPersonal returns true, if message is a personal message,
// returns false if sent to group chat.
func (m Message) IsPersonal() bool {
	return m.Chat != User{}
}

// IsService returns true, if message is a service message,
// returns false otherwise.
//
// Service messages are automatically sent messages, which
// typically occur on some global action. For instance, when
// anyone leaves the chat or chat title changes.
func (m Message) IsService() bool {
	service := false

	if (m.UserJoined != User{}) {
		service = true
	}

	if (m.UserLeft != User{}) {
		service = true
	}

	if m.NewChatTitle != "" {
		service = true
	}

	if len(m.NewChatPhoto) > 0 {
		service = true
	}

	if m.ChatPhotoDeleted {
		service = true
	}

	if m.ChatCreated {
		service = true
	}

	return service
}
<|endoftext|>


<commit_before>// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package source

import (
	"context"
	"go/ast"
	"go/types"

	"golang.org/x/tools/go/types/objectpath"
	"golang.org/x/tools/internal/telemetry/trace"
	errors "golang.org/x/xerrors"
)

// ReferenceInfo holds information about reference to an identifier in Go source.
type ReferenceInfo struct {
	Name string
	mappedRange
	ident         *ast.Ident
	obj           types.Object
	pkg           Package
	isDeclaration bool
}

// References returns a list of references for a given identifier within the packages
// containing i.File. Declarations appear first in the result.
func (i *IdentifierInfo) References(ctx context.Context) ([]*ReferenceInfo, error) {
	ctx, done := trace.StartSpan(ctx, "source.References")
	defer done()

	var references []*ReferenceInfo

	// If the object declaration is nil, assume it is an import spec and do not look for references.
	if i.Declaration.obj == nil {
		return nil, errors.Errorf("no references for an import spec")
	}
	info := i.pkg.GetTypesInfo()
	if info == nil {
		return nil, errors.Errorf("package %s has no types info", i.pkg.PkgPath())
	}
	if i.Declaration.wasImplicit {
		// The definition is implicit, so we must add it separately.
		// This occurs when the variable is declared in a type switch statement
		// or is an implicit package name. Both implicits are local to a file.
		references = append(references, &ReferenceInfo{
			Name:          i.Declaration.obj.Name(),
			mappedRange:   i.Declaration.mappedRange,
			obj:           i.Declaration.obj,
			pkg:           i.pkg,
			isDeclaration: true,
		})
	}
	for ident, obj := range info.Defs {
		if obj == nil || !sameObj(obj, i.Declaration.obj) {
			continue
		}
		rng, err := posToMappedRange(ctx, i.Snapshot.View(), i.pkg, ident.Pos(), ident.End())
		if err != nil {
			return nil, err
		}
		// Add the declarations at the beginning of the references list.
		references = append([]*ReferenceInfo{{
			Name:          ident.Name,
			ident:         ident,
			obj:           obj,
			pkg:           i.pkg,
			isDeclaration: true,
			mappedRange:   rng,
		}}, references...)
	}
	// TODO(matloob): This only needs to look into reverse-dependencies.
	// Avoid checking types of other packages.
	for _, pkg := range i.Snapshot.KnownPackages(ctx) {
		for ident, obj := range pkg.GetTypesInfo().Uses {
			if obj == nil || !(sameObj(obj, i.Declaration.obj)) {
				continue
			}
			rng, err := posToMappedRange(ctx, i.Snapshot.View(), pkg, ident.Pos(), ident.End())
			if err != nil {
				return nil, err
			}
			references = append(references, &ReferenceInfo{
				Name:        ident.Name,
				ident:       ident,
				pkg:         i.pkg,
				obj:         obj,
				mappedRange: rng,
			})
		}
	}
	return references, nil
}

// sameObj returns true if obj is the same as declObj.
// Objects are the same if either they have they have objectpaths
// and their objectpath and package are the same; or if they don't
// have object paths and they have the same Pos and Name.
func sameObj(obj, declObj types.Object) bool {
	// TODO(suzmue): support the case where an identifier may have two different
	// declaration positions.
	if obj.Pkg() == nil || declObj.Pkg() == nil {
		if obj.Pkg() != declObj.Pkg() {
			return false
		}
	} else if obj.Pkg().Path() != declObj.Pkg().Path() {
		return false
	}
	objPath, operr := objectpath.For(obj)
	declObjPath, doperr := objectpath.For(declObj)
	if operr != nil || doperr != nil {
		return obj.Pos() == declObj.Pos() && obj.Name() == declObj.Name()
	}
	return objPath == declObjPath
}
<commit_msg>internal/lsp: don't search other packages for unexported references<commit_after>// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package source

import (
	"context"
	"go/ast"
	"go/types"

	"golang.org/x/tools/go/types/objectpath"
	"golang.org/x/tools/internal/telemetry/trace"
	errors "golang.org/x/xerrors"
)

// ReferenceInfo holds information about reference to an identifier in Go source.
type ReferenceInfo struct {
	Name string
	mappedRange
	ident         *ast.Ident
	obj           types.Object
	pkg           Package
	isDeclaration bool
}

// References returns a list of references for a given identifier within the packages
// containing i.File. Declarations appear first in the result.
func (i *IdentifierInfo) References(ctx context.Context) ([]*ReferenceInfo, error) {
	ctx, done := trace.StartSpan(ctx, "source.References")
	defer done()

	var references []*ReferenceInfo

	// If the object declaration is nil, assume it is an import spec and do not look for references.
	if i.Declaration.obj == nil {
		return nil, errors.Errorf("no references for an import spec")
	}
	info := i.pkg.GetTypesInfo()
	if info == nil {
		return nil, errors.Errorf("package %s has no types info", i.pkg.PkgPath())
	}
	if i.Declaration.wasImplicit {
		// The definition is implicit, so we must add it separately.
		// This occurs when the variable is declared in a type switch statement
		// or is an implicit package name. Both implicits are local to a file.
		references = append(references, &ReferenceInfo{
			Name:          i.Declaration.obj.Name(),
			mappedRange:   i.Declaration.mappedRange,
			obj:           i.Declaration.obj,
			pkg:           i.pkg,
			isDeclaration: true,
		})
	}
	for ident, obj := range info.Defs {
		if obj == nil || !sameObj(obj, i.Declaration.obj) {
			continue
		}
		rng, err := posToMappedRange(ctx, i.Snapshot.View(), i.pkg, ident.Pos(), ident.End())
		if err != nil {
			return nil, err
		}
		// Add the declarations at the beginning of the references list.
		references = append([]*ReferenceInfo{{
			Name:          ident.Name,
			ident:         ident,
			obj:           obj,
			pkg:           i.pkg,
			isDeclaration: true,
			mappedRange:   rng,
		}}, references...)
	}
	var searchpkgs []Package
	if i.Declaration.obj.Exported() {
		// Only search all packages if the identifier is exported.
		// TODO(matloob): This only needs to look into reverse-dependencies.
		// Avoid checking types of other packages.
		searchpkgs = i.Snapshot.KnownPackages(ctx)
	} else {
		searchpkgs = []Package{i.pkg}
	}
	for _, pkg := range searchpkgs {
		for ident, obj := range pkg.GetTypesInfo().Uses {
			if obj == nil || !(sameObj(obj, i.Declaration.obj)) {
				continue
			}
			rng, err := posToMappedRange(ctx, i.Snapshot.View(), pkg, ident.Pos(), ident.End())
			if err != nil {
				return nil, err
			}
			references = append(references, &ReferenceInfo{
				Name:        ident.Name,
				ident:       ident,
				pkg:         i.pkg,
				obj:         obj,
				mappedRange: rng,
			})
		}
	}
	return references, nil
}

// sameObj returns true if obj is the same as declObj.
// Objects are the same if either they have they have objectpaths
// and their objectpath and package are the same; or if they don't
// have object paths and they have the same Pos and Name.
func sameObj(obj, declObj types.Object) bool {
	// TODO(suzmue): support the case where an identifier may have two different
	// declaration positions.
	if obj.Pkg() == nil || declObj.Pkg() == nil {
		if obj.Pkg() != declObj.Pkg() {
			return false
		}
	} else if obj.Pkg().Path() != declObj.Pkg().Path() {
		return false
	}
	objPath, operr := objectpath.For(obj)
	declObjPath, doperr := objectpath.For(declObj)
	if operr != nil || doperr != nil {
		return obj.Pos() == declObj.Pos() && obj.Name() == declObj.Name()
	}
	return objPath == declObjPath
}
<|endoftext|>


<commit_before>// Copyright 2015 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.

package wl2k

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"mime"
	"net/textproto"
	"strconv"
	"strings"
	"time"
)

// Representation of a receiver/sender address.
type Address struct {
	Proto string
	Addr  string
}

// File represents an attachment.
type File struct {
	data []byte
	name string
	err  error
}

// Message represent the Winlink 2000 Message Structure as defined in http://winlink.org/B2F.
type Message struct {
	// The header names are case-insensitive.
	//
	// Users should normally access common header fields
	// using the appropriate Message methods.
	Header Header

	body  []byte
	files []*File
}

type MsgType string

const (
	Private        MsgType = "Private"
	Service                = "Service"
	Inquiry                = "Inquiry"
	PositionReport         = "Position Report"
	Option                 = "Option"
	System                 = "System"
)

// NewMessage initializes and returns a new message with Type, Mbo, From and Date set.
//
// If the message type t is empty, it defaults to Private.
func NewMessage(t MsgType, mycall string) *Message {
	msg := &Message{
		Header: make(Header),
	}

	msg.Header.Set(HEADER_MID, GenerateMid(mycall))

	msg.SetDate(time.Now())
	msg.SetFrom(mycall)
	msg.Header.Set(HEADER_MBO, mycall)

	if t == "" {
		t = Private
	}
	msg.Header.Set(HEADER_TYPE, string(t))

	return msg
}

// MID returns the unique identifier of this message across the winlink system.
func (m *Message) MID() string { return m.Header.Get(HEADER_MID) }

// SetSubject sets this message's subject field.
func (m *Message) SetSubject(str string) { m.Header.Set(HEADER_SUBJECT, str) }

// Subject returns this message's subject field.
func (m *Message) Subject() string { return m.Header.Get(HEADER_SUBJECT) }

// Type returns the message type.
//
// See MsgType consts for details.
func (m *Message) Type() MsgType { return MsgType(m.Header.Get(HEADER_TYPE)) }

// Mbo returns the mailbox operator origin of this message.
func (m *Message) Mbo() string { return m.Header.Get(HEADER_MBO) }

// Body returns this message's body encoded as utf8.
func (m *Message) Body() (string, error) { return BodyFromBytes(m.body, m.Charset()) }

// Files returns the message attachments.
func (m *Message) Files() []*File { return m.files }

// SetFrom sets the From header field.
//
// SMTP: prefix is automatically added if needed, see AddressFromString.
func (m *Message) SetFrom(addr string) { m.Header.Set(HEADER_FROM, AddressFromString(addr).String()) }

// From returns the From header field as an Address.
func (m *Message) From() Address { return AddressFromString(m.Header.Get(HEADER_FROM)) }

// Set date sets the Date header field.
//
// The field is set in the format DateLayout, UTC.
func (m *Message) SetDate(t time.Time) { m.Header.Set(HEADER_DATE, t.UTC().Format(DateLayout)) }

// Date parses the Date header field according to the winlink format.
//
// Parse errors are omitted, but it's checked at serialization.
func (m *Message) Date() time.Time {
	date, _ := ParseDate(m.Header.Get(HEADER_DATE))
	return date
}

// SetBody sets the given string as message body.
//
// The body is encoded with the character encoding given by m.Charset().
// All lines are modified to ensure CRLF.
func (m *Message) SetBody(body string) error {
	bytes, err := StringToBody(body, m.Charset())
	if err != nil {
		return err
	}

	m.body = bytes
	m.Header.Set(HEADER_BODY, fmt.Sprintf("%d", len(bytes)))
	return nil
}

// BodySize returns the expected size of the body (in bytes) as defined in the header.
func (m *Message) BodySize() int { size, _ := strconv.Atoi(m.Header.Get(HEADER_BODY)); return size }

// Charset returns the body character encoding as defined in the ContentType header field.
//
// If the header field is unset, DefaultCharset is returned.
func (m *Message) Charset() string {
	_, params, err := mime.ParseMediaType(m.Header.Get(HEADER_CONTENT_TYPE))
	if err != nil {
		return DefaultCharset
	}

	if v, ok := params["charset"]; ok {
		return v
	}
	return DefaultCharset
}

// AddTo adds a new receiver for this message.
//
// It adds a new To header field per given address.
// SMTP: prefix is automatically added if needed, see AddressFromString.
func (m *Message) AddTo(addr ...string) {
	for _, a := range addr {
		m.Header.Add(HEADER_TO, AddressFromString(a).String())
	}
}

// AddCc adds a new carbon copy receiver to this message.
//
// It adds a new Cc header field per given address.
// SMTP: prefix is automatically added if needed, see AddressFromString.
func (m *Message) AddCc(addr ...string) {
	for _, a := range addr {
		m.Header.Add(HEADER_CC, AddressFromString(a).String())
	}
}

// To returns primary receivers of this message.
func (m *Message) To() (to []Address) {
	for _, str := range m.Header[HEADER_TO] {
		to = append(to, AddressFromString(str))
	}
	return
}

// Cc returns the carbon copy receivers of this message.
func (m *Message) Cc() (cc []Address) {
	for _, str := range m.Header[HEADER_CC] {
		cc = append(cc, AddressFromString(str))
	}
	return
}

// Implements ReaderFrom for Message.
//
// Reads the given io.Reader and fills in values fetched from the stream.
func (m *Message) ReadFrom(r io.Reader) error {
	reader := bufio.NewReader(r)

	if h, err := textproto.NewReader(reader).ReadMIMEHeader(); err != nil {
		return err
	} else {
		m.Header = Header(h)
	}

	// Read body
	var err error
	m.body, err = readSection(reader, m.BodySize())
	if err != nil {
		return err
	}

	// Read files
	m.files = make([]*File, len(m.Header[HEADER_FILE]))
	for i, value := range m.Header[HEADER_FILE] {
		file := new(File)
		m.files[i] = file

		slice := strings.SplitN(value, ` `, 2)
		if len(slice) != 2 {
			file.err = errors.New(`Failed to parse file header. Got: ` + value)
			continue
		}

		size, _ := strconv.Atoi(slice[0])
		file.name = slice[1]

		file.data, err = readSection(reader, size)
		if err != nil {
			file.err = err
		}
	}

	// Return error if date field is not parseable
	if err == nil {
		_, err = ParseDate(m.Header.Get(HEADER_DATE))
	}

	return err
}

func readSection(reader *bufio.Reader, readN int) ([]byte, error) {
	buf := make([]byte, readN)

	var err error
	n := 0
	for n < readN {
		m, err := reader.Read(buf[n:])
		if err != nil {
			break
		}
		n += m
	}

	if err != nil {
		return buf, err
	}

	end, err := reader.ReadString('\n')
	switch {
	case n != readN:
		return buf, io.ErrUnexpectedEOF
	case err == io.EOF:
		// That's ok
	case err != nil:
		return buf, err
	case end != "\r\n":
		return buf, errors.New("Unexpected end of section")
	}
	return buf, nil
}

// Returns true if the given Address is the only receiver of this Message.
func (m *Message) IsOnlyReceiver(addr Address) bool {
	receivers := m.Receivers()
	if len(receivers) != 1 {
		return false
	}
	return receivers[0].String() == addr.String()
}

// Method for generating a proposal of the message.
func (m *Message) Proposal() (*Proposal, error) {
	data, err := m.Bytes()
	if err != nil {
		return nil, err
	}

	return NewProposal(m.MID(), m.Subject(), data), nil
}

// Receivers returns a slice of all receivers of this message.
func (m *Message) Receivers() []Address {
	to, cc := m.To(), m.Cc()
	addrs := make([]Address, 0, len(to)+len(cc))
	if len(to) > 0 {
		addrs = append(addrs, to...)
	}
	if len(cc) > 0 {
		addrs = append(addrs, cc...)
	}
	return addrs
}

// AddFile adds the given File as an attachment to m.
func (m *Message) AddFile(f *File) {
	m.files = append(m.files, f)

	// Add header
	value := fmt.Sprintf("%d %s", f.Size(), f.Name())
	m.Header[HEADER_FILE] = append(m.Header[HEADER_FILE], value)
}

// Bytes returns the message in the Winlink Message format.
func (m *Message) Bytes() ([]byte, error) {
	var buf bytes.Buffer
	if err := m.Write(&buf); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

// Writes Message to the given Writer in the Winlink Message format.
//
// If the Date header field is not formatted correctly, an error will be returned.
func (m *Message) Write(w io.Writer) (err error) {
	// Ensure Date field is in correct format
	if _, err = ParseDate(m.Header.Get(HEADER_DATE)); err != nil {
		return
	}

	// We use a bufio.Writer to defer error handling until Flush
	writer := bufio.NewWriter(w)

	// Header
	m.Header.Write(writer)
	writer.WriteString("\r\n") // end of headers

	// Body
	writer.Write(m.body)
	if len(m.Files()) > 0 {
		writer.WriteString("\r\n") // end of body
	}

	// Files (the order must be the same as they appear in the header)
	for _, f := range m.Files() {
		writer.Write(f.data)
		writer.WriteString("\r\n") // end of file
	}

	return writer.Flush()
}

// Message stringer.
func (m *Message) String() string {
	buf := bytes.NewBufferString(``)
	w := bufio.NewWriter(buf)

	fmt.Fprintln(w, "MID: ", m.MID())
	fmt.Fprintln(w, `Date:`, m.Date())
	fmt.Fprintln(w, `From:`, m.From())
	for _, to := range m.To() {
		fmt.Fprintln(w, `To:`, to)
	}
	for _, cc := range m.Cc() {
		fmt.Fprintln(w, `Cc:`, cc)
	}
	fmt.Fprintln(w, `Subject:`, m.Subject())

	body, _ := m.Body()
	fmt.Fprintf(w, "\n%s\n", body)

	fmt.Fprintln(w, "Attachments:")
	for _, f := range m.Files() {
		fmt.Fprintf(w, "\t%s [%d bytes]\n", f.Name(), f.Size())
	}

	w.Flush()
	return string(buf.Bytes())
}

// JSON marshaller for File.
func (f *File) MarshalJSON() ([]byte, error) {
	b, err := json.Marshal(struct {
		Name string
		Size int
	}{f.Name(), f.Size()})
	return b, err
}

// Name returns the attachment's filename.
func (f *File) Name() string { return f.name }

// Size returns the attachments's size in bytes.
func (f *File) Size() int { return len(f.data) }

// Data returns a copy of the attachment content.
func (f *File) Data() []byte {
	cpy := make([]byte, len(f.data))
	copy(cpy, f.data)
	return cpy
}

// Create a new file (attachment) with the given name and data.
func NewFile(name string, data []byte) *File {
	return &File{
		data: data,
		name: name,
	}
}

// Textual representation of Address.
func (a Address) String() string {
	if a.Proto == "" {
		return a.Addr
	} else {
		return fmt.Sprintf("%s:%s", a.Proto, a.Addr)
	}
}

// IsZero reports whether the Address is unset.
func (a Address) IsZero() bool { return len(a.Addr) == 0 }

// EqualString reports whether the given address string is equal to this address.
func (a Address) EqualString(b string) bool { return a == AddressFromString(b) }

// Function that constructs a proper Address from a string.
//
// Supported formats: foo@bar.baz (SMTP proto), N0CALL (short winlink address) or N0CALL@winlink.org (full winlink address).
func AddressFromString(addr string) Address {
	if parts := strings.Split(addr, ":"); len(parts) == 2 {
		return Address{Proto: parts[0], Addr: parts[1]}
	}
	if parts := strings.Split(addr, "@"); len(parts) == 1 {
		return Address{Addr: addr}
	} else if strings.EqualFold(parts[1], "winlink.org") {
		return Address{Addr: parts[0]}
	} else {
		return Address{Proto: "SMTP", Addr: addr}
	}
}

func ParseDate(dateStr string) (time.Time, error) {
	if dateStr == "" {
		return time.Time{}, nil
	}

	date, err := time.Parse(DateLayout, dateStr)
	if err != nil {
		return date, err
	}

	return date.Local(), nil
}
<commit_msg>wl2k: Ensure Content-Type and Content-Transfer-Encoding are set.<commit_after>// Copyright 2015 Martin Hebnes Pedersen (LA5NTA). All rights reserved.
// Use of this source code is governed by the MIT-license that can be
// found in the LICENSE file.

package wl2k

import (
	"bufio"
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"mime"
	"net/textproto"
	"strconv"
	"strings"
	"time"
)

// Representation of a receiver/sender address.
type Address struct {
	Proto string
	Addr  string
}

// File represents an attachment.
type File struct {
	data []byte
	name string
	err  error
}

// Message represent the Winlink 2000 Message Structure as defined in http://winlink.org/B2F.
type Message struct {
	// The header names are case-insensitive.
	//
	// Users should normally access common header fields
	// using the appropriate Message methods.
	Header Header

	body  []byte
	files []*File
}

type MsgType string

const (
	Private        MsgType = "Private"
	Service                = "Service"
	Inquiry                = "Inquiry"
	PositionReport         = "Position Report"
	Option                 = "Option"
	System                 = "System"
)

// NewMessage initializes and returns a new message with Type, Mbo, From and Date set.
//
// If the message type t is empty, it defaults to Private.
func NewMessage(t MsgType, mycall string) *Message {
	msg := &Message{
		Header: make(Header),
	}

	msg.Header.Set(HEADER_MID, GenerateMid(mycall))

	msg.SetDate(time.Now())
	msg.SetFrom(mycall)
	msg.Header.Set(HEADER_MBO, mycall)

	if t == "" {
		t = Private
	}
	msg.Header.Set(HEADER_TYPE, string(t))

	return msg
}

// MID returns the unique identifier of this message across the winlink system.
func (m *Message) MID() string { return m.Header.Get(HEADER_MID) }

// SetSubject sets this message's subject field.
func (m *Message) SetSubject(str string) { m.Header.Set(HEADER_SUBJECT, str) }

// Subject returns this message's subject field.
func (m *Message) Subject() string { return m.Header.Get(HEADER_SUBJECT) }

// Type returns the message type.
//
// See MsgType consts for details.
func (m *Message) Type() MsgType { return MsgType(m.Header.Get(HEADER_TYPE)) }

// Mbo returns the mailbox operator origin of this message.
func (m *Message) Mbo() string { return m.Header.Get(HEADER_MBO) }

// Body returns this message's body encoded as utf8.
func (m *Message) Body() (string, error) { return BodyFromBytes(m.body, m.Charset()) }

// Files returns the message attachments.
func (m *Message) Files() []*File { return m.files }

// SetFrom sets the From header field.
//
// SMTP: prefix is automatically added if needed, see AddressFromString.
func (m *Message) SetFrom(addr string) { m.Header.Set(HEADER_FROM, AddressFromString(addr).String()) }

// From returns the From header field as an Address.
func (m *Message) From() Address { return AddressFromString(m.Header.Get(HEADER_FROM)) }

// Set date sets the Date header field.
//
// The field is set in the format DateLayout, UTC.
func (m *Message) SetDate(t time.Time) { m.Header.Set(HEADER_DATE, t.UTC().Format(DateLayout)) }

// Date parses the Date header field according to the winlink format.
//
// Parse errors are omitted, but it's checked at serialization.
func (m *Message) Date() time.Time {
	date, _ := ParseDate(m.Header.Get(HEADER_DATE))
	return date
}

// SetBodyWithCharset translates and sets the body according to given charset.
//
// Header field Content-Transfer-Encoding is set to DefaultTransferEncoding.
// Header field Content-Type is set according to charset.
// All lines are modified to ensure CRLF.
//
// Use SetBody to use default character encoding.
func (m *Message) SetBodyWithCharset(charset, body string) error {
	m.Header.Set(HEADER_CONTENT_TRANSFER_ENCODING, DefaultTransferEncoding)
	m.Header.Set(HEADER_CONTENT_TYPE, mime.FormatMediaType(
		"text/plain",
		map[string]string{"charset": DefaultCharset},
	))

	bytes, err := StringToBody(body, DefaultCharset)
	if err != nil {
		return err
	}

	m.body = bytes
	m.Header.Set(HEADER_BODY, fmt.Sprintf("%d", len(bytes)))
	return nil
}

// SetBody sets the given string as message body using DefaultCharset.
//
// See SetBodyWithCharset for more info.
func (m *Message) SetBody(body string) error {
	return m.SetBodyWithCharset(DefaultCharset, body)
}

// BodySize returns the expected size of the body (in bytes) as defined in the header.
func (m *Message) BodySize() int { size, _ := strconv.Atoi(m.Header.Get(HEADER_BODY)); return size }

// Charset returns the body character encoding as defined in the ContentType header field.
//
// If the header field is unset, DefaultCharset is returned.
func (m *Message) Charset() string {
	_, params, err := mime.ParseMediaType(m.Header.Get(HEADER_CONTENT_TYPE))
	if err != nil {
		return DefaultCharset
	}

	if v, ok := params["charset"]; ok {
		return v
	}
	return DefaultCharset
}

// AddTo adds a new receiver for this message.
//
// It adds a new To header field per given address.
// SMTP: prefix is automatically added if needed, see AddressFromString.
func (m *Message) AddTo(addr ...string) {
	for _, a := range addr {
		m.Header.Add(HEADER_TO, AddressFromString(a).String())
	}
}

// AddCc adds a new carbon copy receiver to this message.
//
// It adds a new Cc header field per given address.
// SMTP: prefix is automatically added if needed, see AddressFromString.
func (m *Message) AddCc(addr ...string) {
	for _, a := range addr {
		m.Header.Add(HEADER_CC, AddressFromString(a).String())
	}
}

// To returns primary receivers of this message.
func (m *Message) To() (to []Address) {
	for _, str := range m.Header[HEADER_TO] {
		to = append(to, AddressFromString(str))
	}
	return
}

// Cc returns the carbon copy receivers of this message.
func (m *Message) Cc() (cc []Address) {
	for _, str := range m.Header[HEADER_CC] {
		cc = append(cc, AddressFromString(str))
	}
	return
}

// Implements ReaderFrom for Message.
//
// Reads the given io.Reader and fills in values fetched from the stream.
func (m *Message) ReadFrom(r io.Reader) error {
	reader := bufio.NewReader(r)

	if h, err := textproto.NewReader(reader).ReadMIMEHeader(); err != nil {
		return err
	} else {
		m.Header = Header(h)
	}

	// Read body
	var err error
	m.body, err = readSection(reader, m.BodySize())
	if err != nil {
		return err
	}

	// Read files
	m.files = make([]*File, len(m.Header[HEADER_FILE]))
	for i, value := range m.Header[HEADER_FILE] {
		file := new(File)
		m.files[i] = file

		slice := strings.SplitN(value, ` `, 2)
		if len(slice) != 2 {
			file.err = errors.New(`Failed to parse file header. Got: ` + value)
			continue
		}

		size, _ := strconv.Atoi(slice[0])
		file.name = slice[1]

		file.data, err = readSection(reader, size)
		if err != nil {
			file.err = err
		}
	}

	// Return error if date field is not parseable
	if err == nil {
		_, err = ParseDate(m.Header.Get(HEADER_DATE))
	}

	return err
}

func readSection(reader *bufio.Reader, readN int) ([]byte, error) {
	buf := make([]byte, readN)

	var err error
	n := 0
	for n < readN {
		m, err := reader.Read(buf[n:])
		if err != nil {
			break
		}
		n += m
	}

	if err != nil {
		return buf, err
	}

	end, err := reader.ReadString('\n')
	switch {
	case n != readN:
		return buf, io.ErrUnexpectedEOF
	case err == io.EOF:
		// That's ok
	case err != nil:
		return buf, err
	case end != "\r\n":
		return buf, errors.New("Unexpected end of section")
	}
	return buf, nil
}

// Returns true if the given Address is the only receiver of this Message.
func (m *Message) IsOnlyReceiver(addr Address) bool {
	receivers := m.Receivers()
	if len(receivers) != 1 {
		return false
	}
	return receivers[0].String() == addr.String()
}

// Method for generating a proposal of the message.
func (m *Message) Proposal() (*Proposal, error) {
	data, err := m.Bytes()
	if err != nil {
		return nil, err
	}

	return NewProposal(m.MID(), m.Subject(), data), nil
}

// Receivers returns a slice of all receivers of this message.
func (m *Message) Receivers() []Address {
	to, cc := m.To(), m.Cc()
	addrs := make([]Address, 0, len(to)+len(cc))
	if len(to) > 0 {
		addrs = append(addrs, to...)
	}
	if len(cc) > 0 {
		addrs = append(addrs, cc...)
	}
	return addrs
}

// AddFile adds the given File as an attachment to m.
func (m *Message) AddFile(f *File) {
	m.files = append(m.files, f)

	// Add header
	value := fmt.Sprintf("%d %s", f.Size(), f.Name())
	m.Header[HEADER_FILE] = append(m.Header[HEADER_FILE], value)
}

// Bytes returns the message in the Winlink Message format.
func (m *Message) Bytes() ([]byte, error) {
	var buf bytes.Buffer
	if err := m.Write(&buf); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}

// Writes Message to the given Writer in the Winlink Message format.
//
// If the Date header field is not formatted correctly, an error will be returned.
func (m *Message) Write(w io.Writer) (err error) {
	// Ensure Date field is in correct format
	if _, err = ParseDate(m.Header.Get(HEADER_DATE)); err != nil {
		return
	}

	// We use a bufio.Writer to defer error handling until Flush
	writer := bufio.NewWriter(w)

	// Header
	m.Header.Write(writer)
	writer.WriteString("\r\n") // end of headers

	// Body
	writer.Write(m.body)
	if len(m.Files()) > 0 {
		writer.WriteString("\r\n") // end of body
	}

	// Files (the order must be the same as they appear in the header)
	for _, f := range m.Files() {
		writer.Write(f.data)
		writer.WriteString("\r\n") // end of file
	}

	return writer.Flush()
}

// Message stringer.
func (m *Message) String() string {
	buf := bytes.NewBufferString(``)
	w := bufio.NewWriter(buf)

	fmt.Fprintln(w, "MID: ", m.MID())
	fmt.Fprintln(w, `Date:`, m.Date())
	fmt.Fprintln(w, `From:`, m.From())
	for _, to := range m.To() {
		fmt.Fprintln(w, `To:`, to)
	}
	for _, cc := range m.Cc() {
		fmt.Fprintln(w, `Cc:`, cc)
	}
	fmt.Fprintln(w, `Subject:`, m.Subject())

	body, _ := m.Body()
	fmt.Fprintf(w, "\n%s\n", body)

	fmt.Fprintln(w, "Attachments:")
	for _, f := range m.Files() {
		fmt.Fprintf(w, "\t%s [%d bytes]\n", f.Name(), f.Size())
	}

	w.Flush()
	return string(buf.Bytes())
}

// JSON marshaller for File.
func (f *File) MarshalJSON() ([]byte, error) {
	b, err := json.Marshal(struct {
		Name string
		Size int
	}{f.Name(), f.Size()})
	return b, err
}

// Name returns the attachment's filename.
func (f *File) Name() string { return f.name }

// Size returns the attachments's size in bytes.
func (f *File) Size() int { return len(f.data) }

// Data returns a copy of the attachment content.
func (f *File) Data() []byte {
	cpy := make([]byte, len(f.data))
	copy(cpy, f.data)
	return cpy
}

// Create a new file (attachment) with the given name and data.
func NewFile(name string, data []byte) *File {
	return &File{
		data: data,
		name: name,
	}
}

// Textual representation of Address.
func (a Address) String() string {
	if a.Proto == "" {
		return a.Addr
	} else {
		return fmt.Sprintf("%s:%s", a.Proto, a.Addr)
	}
}

// IsZero reports whether the Address is unset.
func (a Address) IsZero() bool { return len(a.Addr) == 0 }

// EqualString reports whether the given address string is equal to this address.
func (a Address) EqualString(b string) bool { return a == AddressFromString(b) }

// Function that constructs a proper Address from a string.
//
// Supported formats: foo@bar.baz (SMTP proto), N0CALL (short winlink address) or N0CALL@winlink.org (full winlink address).
func AddressFromString(addr string) Address {
	if parts := strings.Split(addr, ":"); len(parts) == 2 {
		return Address{Proto: parts[0], Addr: parts[1]}
	}
	if parts := strings.Split(addr, "@"); len(parts) == 1 {
		return Address{Addr: addr}
	} else if strings.EqualFold(parts[1], "winlink.org") {
		return Address{Addr: parts[0]}
	} else {
		return Address{Proto: "SMTP", Addr: addr}
	}
}

func ParseDate(dateStr string) (time.Time, error) {
	if dateStr == "" {
		return time.Time{}, nil
	}

	date, err := time.Parse(DateLayout, dateStr)
	if err != nil {
		return date, err
	}

	return date.Local(), nil
}
<|endoftext|>


<commit_before>// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package source

import (
	"context"
	"go/ast"
	"go/token"
	"go/types"
	"sort"

	"golang.org/x/tools/internal/event"
	"golang.org/x/tools/internal/lsp/protocol"
	"golang.org/x/tools/internal/span"
	errors "golang.org/x/xerrors"
)

// ReferenceInfo holds information about reference to an identifier in Go source.
type ReferenceInfo struct {
	Name string
	MappedRange
	ident         *ast.Ident
	obj           types.Object
	pkg           Package
	isDeclaration bool
}

// References returns a list of references for a given identifier within the packages
// containing i.File. Declarations appear first in the result.
func References(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position, includeDeclaration bool) ([]*ReferenceInfo, error) {
	ctx, done := event.Start(ctx, "source.References")
	defer done()

	qualifiedObjs, err := qualifiedObjsAtProtocolPos(ctx, s, f, pp)
	// Don't return references for builtin types.
	if errors.Is(err, errBuiltin) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	refs, err := references(ctx, s, qualifiedObjs, includeDeclaration, true)
	if err != nil {
		return nil, err
	}

	toSort := refs
	if includeDeclaration {
		toSort = refs[1:]
	}
	sort.Slice(toSort, func(i, j int) bool {
		x := span.CompareURI(toSort[i].URI(), toSort[j].URI())
		if x == 0 {
			return toSort[i].ident.Pos() < toSort[j].ident.Pos()
		}
		return x < 0
	})
	return refs, nil
}

// references is a helper function to avoid recomputing qualifiedObjsAtProtocolPos.
func references(ctx context.Context, snapshot Snapshot, qos []qualifiedObject, includeDeclaration, includeInterfaceRefs bool) ([]*ReferenceInfo, error) {
	var (
		references []*ReferenceInfo
		seen       = make(map[token.Position]bool)
	)

	filename := snapshot.FileSet().Position(qos[0].obj.Pos()).Filename
	pgf, err := qos[0].pkg.File(span.URIFromPath(filename))
	if err != nil {
		return nil, err
	}
	declIdent, err := findIdentifier(ctx, snapshot, qos[0].pkg, pgf.File, qos[0].obj.Pos())
	if err != nil {
		return nil, err
	}
	// Make sure declaration is the first item in the response.
	if includeDeclaration {
		references = append(references, &ReferenceInfo{
			MappedRange:   declIdent.MappedRange,
			Name:          qos[0].obj.Name(),
			ident:         declIdent.ident,
			obj:           qos[0].obj,
			pkg:           declIdent.pkg,
			isDeclaration: true,
		})
	}

	for _, qo := range qos {
		var searchPkgs []Package

		// Only search dependents if the object is exported.
		if qo.obj.Exported() {
			reverseDeps, err := snapshot.GetReverseDependencies(ctx, qo.pkg.ID())
			if err != nil {
				return nil, err
			}
			searchPkgs = append(searchPkgs, reverseDeps...)
		}
		// Add the package in which the identifier is declared.
		searchPkgs = append(searchPkgs, qo.pkg)
		for _, pkg := range searchPkgs {
			for ident, obj := range pkg.GetTypesInfo().Uses {
				if obj != qo.obj {
					continue
				}
				pos := snapshot.FileSet().Position(ident.Pos())
				if seen[pos] {
					continue
				}
				seen[pos] = true
				rng, err := posToMappedRange(snapshot, pkg, ident.Pos(), ident.End())
				if err != nil {
					return nil, err
				}
				references = append(references, &ReferenceInfo{
					Name:        ident.Name,
					ident:       ident,
					pkg:         pkg,
					obj:         obj,
					MappedRange: rng,
				})
			}
		}
	}

	if includeInterfaceRefs {
		declRange, err := declIdent.Range()
		if err != nil {
			return nil, err
		}
		fh, err := snapshot.GetFile(ctx, declIdent.URI())
		if err != nil {
			return nil, err
		}
		interfaceRefs, err := interfaceReferences(ctx, snapshot, fh, declRange.Start)
		if err != nil {
			return nil, err
		}
		references = append(references, interfaceRefs...)
	}

	return references, nil
}

// interfaceReferences returns the references to the interfaces implemeneted by
// the type or method at the given position.
func interfaceReferences(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position) ([]*ReferenceInfo, error) {
	implementations, err := implementations(ctx, s, f, pp)
	if err != nil {
		if errors.Is(err, ErrNotAType) {
			return nil, nil
		}
		return nil, err
	}

	var refs []*ReferenceInfo
	for _, impl := range implementations {
		implRefs, err := references(ctx, s, []qualifiedObject{impl}, false, false)
		if err != nil {
			return nil, err
		}
		refs = append(refs, implRefs...)
	}
	return refs, nil
}
<commit_msg>internal/lsp/source: don't find possible interface references to types<commit_after>// Copyright 2019 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package source

import (
	"context"
	"go/ast"
	"go/token"
	"go/types"
	"sort"

	"golang.org/x/tools/internal/event"
	"golang.org/x/tools/internal/lsp/protocol"
	"golang.org/x/tools/internal/span"
	errors "golang.org/x/xerrors"
)

// ReferenceInfo holds information about reference to an identifier in Go source.
type ReferenceInfo struct {
	Name string
	MappedRange
	ident         *ast.Ident
	obj           types.Object
	pkg           Package
	isDeclaration bool
}

// References returns a list of references for a given identifier within the packages
// containing i.File. Declarations appear first in the result.
func References(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position, includeDeclaration bool) ([]*ReferenceInfo, error) {
	ctx, done := event.Start(ctx, "source.References")
	defer done()

	qualifiedObjs, err := qualifiedObjsAtProtocolPos(ctx, s, f, pp)
	// Don't return references for builtin types.
	if errors.Is(err, errBuiltin) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}

	refs, err := references(ctx, s, qualifiedObjs, includeDeclaration, true)
	if err != nil {
		return nil, err
	}

	toSort := refs
	if includeDeclaration {
		toSort = refs[1:]
	}
	sort.Slice(toSort, func(i, j int) bool {
		x := span.CompareURI(toSort[i].URI(), toSort[j].URI())
		if x == 0 {
			return toSort[i].ident.Pos() < toSort[j].ident.Pos()
		}
		return x < 0
	})
	return refs, nil
}

// references is a helper function to avoid recomputing qualifiedObjsAtProtocolPos.
func references(ctx context.Context, snapshot Snapshot, qos []qualifiedObject, includeDeclaration, includeInterfaceRefs bool) ([]*ReferenceInfo, error) {
	var (
		references []*ReferenceInfo
		seen       = make(map[token.Position]bool)
	)

	filename := snapshot.FileSet().Position(qos[0].obj.Pos()).Filename
	pgf, err := qos[0].pkg.File(span.URIFromPath(filename))
	if err != nil {
		return nil, err
	}
	declIdent, err := findIdentifier(ctx, snapshot, qos[0].pkg, pgf.File, qos[0].obj.Pos())
	if err != nil {
		return nil, err
	}
	// Make sure declaration is the first item in the response.
	if includeDeclaration {
		references = append(references, &ReferenceInfo{
			MappedRange:   declIdent.MappedRange,
			Name:          qos[0].obj.Name(),
			ident:         declIdent.ident,
			obj:           qos[0].obj,
			pkg:           declIdent.pkg,
			isDeclaration: true,
		})
	}

	for _, qo := range qos {
		var searchPkgs []Package

		// Only search dependents if the object is exported.
		if qo.obj.Exported() {
			reverseDeps, err := snapshot.GetReverseDependencies(ctx, qo.pkg.ID())
			if err != nil {
				return nil, err
			}
			searchPkgs = append(searchPkgs, reverseDeps...)
		}
		// Add the package in which the identifier is declared.
		searchPkgs = append(searchPkgs, qo.pkg)
		for _, pkg := range searchPkgs {
			for ident, obj := range pkg.GetTypesInfo().Uses {
				if obj != qo.obj {
					continue
				}
				pos := snapshot.FileSet().Position(ident.Pos())
				if seen[pos] {
					continue
				}
				seen[pos] = true
				rng, err := posToMappedRange(snapshot, pkg, ident.Pos(), ident.End())
				if err != nil {
					return nil, err
				}
				references = append(references, &ReferenceInfo{
					Name:        ident.Name,
					ident:       ident,
					pkg:         pkg,
					obj:         obj,
					MappedRange: rng,
				})
			}
		}
	}

	// When searching on type name, don't include interface references -- they
	// would be things like all references to Stringer for any type that
	// happened to have a String method.
	_, isType := declIdent.Declaration.obj.(*types.TypeName)
	if includeInterfaceRefs && !isType {
		declRange, err := declIdent.Range()
		if err != nil {
			return nil, err
		}
		fh, err := snapshot.GetFile(ctx, declIdent.URI())
		if err != nil {
			return nil, err
		}
		interfaceRefs, err := interfaceReferences(ctx, snapshot, fh, declRange.Start)
		if err != nil {
			return nil, err
		}
		references = append(references, interfaceRefs...)
	}

	return references, nil
}

// interfaceReferences returns the references to the interfaces implemeneted by
// the type or method at the given position.
func interfaceReferences(ctx context.Context, s Snapshot, f FileHandle, pp protocol.Position) ([]*ReferenceInfo, error) {
	implementations, err := implementations(ctx, s, f, pp)
	if err != nil {
		if errors.Is(err, ErrNotAType) {
			return nil, nil
		}
		return nil, err
	}

	var refs []*ReferenceInfo
	for _, impl := range implementations {
		implRefs, err := references(ctx, s, []qualifiedObject{impl}, false, false)
		if err != nil {
			return nil, err
		}
		refs = append(refs, implRefs...)
	}
	return refs, nil
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
)

func printNginxBuildVersion() {
	fmt.Printf(`nginx-build %s
Compiler: %s %s
Copyright (C) 2014-2020 Tatsuhiko Kubo <cubicdaiya@gmail.com>
`,
		NginxBuildVersion,
		runtime.Compiler,
		runtime.Version())

}

func printConfigureOptions() error {
	cmd := exec.Command("objs/nginx", "-V")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func printFirstMsg() {
	fmt.Printf(`nginx-build: %s
Compiler: %s %s
`,
		NginxBuildVersion,
		runtime.Compiler,
		runtime.Version())
}

func printLastMsg(workDir, srcDir string, openResty, configureOnly bool) {
	log.Println("Complete building nginx!")

	if !openResty {
		if !configureOnly {
			fmt.Println()
			err := printConfigureOptions()
			if err != nil {
				fmt.Println(err.Error())
			}
		}
	}
	fmt.Println()

	lastMsgFormat := `Enter the following command for install nginx.

   $ cd %s/%s%s
   $ sudo make install
`
	if configureOnly {
		log.Printf(lastMsgFormat, workDir, srcDir, "\n   $ make")
	} else {
		log.Printf(lastMsgFormat, workDir, srcDir, "")
	}
}

func usage() {
	fmt.Fprintf(os.Stdout, "Usage of %s:\n", os.Args[0])
	flag.VisitAll(func(f *flag.Flag) {
		if !isNginxBuildOption(f.Name) {
			return
		}
		s := fmt.Sprintf("  -%s", f.Name)
		s += "\n\t"
		s += f.Usage
		defValue := defaultStringValue(f.Name)
		if defValue != "" {
			s += fmt.Sprintf(" ( default: %s )", defValue)
		}

		fmt.Fprintf(os.Stdout, "%s\n", s)
	})
	fmt.Fprintf(os.Stdout, `
And nginx-build accepts nginx-self options directly.
`)
}
<commit_msg>copyright: update year.<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"os/exec"
	"runtime"
)

func printNginxBuildVersion() {
	fmt.Printf(`nginx-build %s
Compiler: %s %s
Copyright (C) 2014-2021 Tatsuhiko Kubo <cubicdaiya@gmail.com>
`,
		NginxBuildVersion,
		runtime.Compiler,
		runtime.Version())

}

func printConfigureOptions() error {
	cmd := exec.Command("objs/nginx", "-V")
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func printFirstMsg() {
	fmt.Printf(`nginx-build: %s
Compiler: %s %s
`,
		NginxBuildVersion,
		runtime.Compiler,
		runtime.Version())
}

func printLastMsg(workDir, srcDir string, openResty, configureOnly bool) {
	log.Println("Complete building nginx!")

	if !openResty {
		if !configureOnly {
			fmt.Println()
			err := printConfigureOptions()
			if err != nil {
				fmt.Println(err.Error())
			}
		}
	}
	fmt.Println()

	lastMsgFormat := `Enter the following command for install nginx.

   $ cd %s/%s%s
   $ sudo make install
`
	if configureOnly {
		log.Printf(lastMsgFormat, workDir, srcDir, "\n   $ make")
	} else {
		log.Printf(lastMsgFormat, workDir, srcDir, "")
	}
}

func usage() {
	fmt.Fprintf(os.Stdout, "Usage of %s:\n", os.Args[0])
	flag.VisitAll(func(f *flag.Flag) {
		if !isNginxBuildOption(f.Name) {
			return
		}
		s := fmt.Sprintf("  -%s", f.Name)
		s += "\n\t"
		s += f.Usage
		defValue := defaultStringValue(f.Name)
		if defValue != "" {
			s += fmt.Sprintf(" ( default: %s )", defValue)
		}

		fmt.Fprintf(os.Stdout, "%s\n", s)
	})
	fmt.Fprintf(os.Stdout, `
And nginx-build accepts nginx-self options directly.
`)
}
<|endoftext|>


<commit_before>package s2k

import (
	"fmt"

	"github.com/spiegel-im-spiegel/gpgpdump/internal/options"
	"github.com/spiegel-im-spiegel/gpgpdump/internal/parse/values"
)

//const
const EXPBIAS = uint32(6)

// S2K - information of public key algorithm
type S2K struct {
	*options.Options
	buf  []byte
	left int
}

//New returns new Pubkey
func New(opt *options.Options, buf []byte) *S2K {
	return &S2K{Options: opt, buf: buf}
}

//Left returns left bytes
func (s S2K) Left() int {
	return s.left
}

//Parse parsing S2K information
func (s *S2K) Parse(indent values.Indent) values.Content {
	content := values.NewContent()
	s2kAlg := values.S2KAlg(s.buf[0])
	s.left = len(s.buf) - 1

	content = append(content, indent.Fill(s2kAlg.String()))
	switch s2kAlg {
	case 0:
		content = append(content, (indent + 1).Fill(values.HashAlg(s.buf[1]).String()))
		s.left--
	case 1:
		content = append(content, (indent + 1).Fill(values.HashAlg(s.buf[1]).String()))
		content = append(content, (indent + 1).Fill(fmt.Sprintf("Salt - %s", values.DumpByte(s.buf[2:10]))))
		s.left -= 9
	case 3:
		content = append(content, (indent + 1).Fill(values.HashAlg(s.buf[1]).String()))
		content = append(content, (indent + 1).Fill(fmt.Sprintf("Salt - %s", values.DumpByte(s.buf[2:10]))))
		c := uint32(s.buf[10])
		count := (uint32(16) + (c & 15)) << ((c >> 4) + EXPBIAS)
		content = append(content, (indent + 1).Fill(fmt.Sprintf("Count - %d (coded count 0x%02x)", count, c)))
		s.left -= 10
	case 101:
		mrk := string(s.buf[1:5])
		switch mrk {
		case "GNU1":
			content = append(content, (indent + 1).Fill("GnuPG gnu-dummy (s2k 1001)"))
		case "GNU2":
			content = append(content, (indent + 1).Fill("GnuPG gnu-divert-to-card (s2k 1001)"))
			l := s.buf[5]
			content = append(content, (indent + 2).Fill(fmt.Sprintf("Serial Number: %s", values.DumpByte(s.buf[6:6+1]))))
			s.left -= 5 + int(l)
		default:
		}
	}
	return content
}
<commit_msg>fix bug.<commit_after>package s2k

import (
	"fmt"

	"github.com/spiegel-im-spiegel/gpgpdump/internal/options"
	"github.com/spiegel-im-spiegel/gpgpdump/internal/parse/values"
)

//const
const EXPBIAS = uint32(6)

// S2K - information of public key algorithm
type S2K struct {
	*options.Options
	buf  []byte
	left int
}

//New returns new Pubkey
func New(opt *options.Options, buf []byte) *S2K {
	return &S2K{Options: opt, buf: buf}
}

//Left returns left bytes
func (s S2K) Left() int {
	return s.left
}

//Parse parsing S2K information
func (s *S2K) Parse(indent values.Indent) values.Content {
	content := values.NewContent()
	s2kAlg := values.S2KAlg(s.buf[0])
	s.left = len(s.buf) - 1

	content = append(content, indent.Fill(s2kAlg.String()))
	switch s2kAlg {
	case 0:
		content = append(content, (indent + 1).Fill(values.HashAlg(s.buf[1]).String()))
		s.left--
	case 1:
		content = append(content, (indent + 1).Fill(values.HashAlg(s.buf[1]).String()))
		content = append(content, (indent + 1).Fill(fmt.Sprintf("Salt - %s", values.DumpByte(s.buf[2:10]))))
		s.left -= 9
	case 3:
		content = append(content, (indent + 1).Fill(values.HashAlg(s.buf[1]).String()))
		content = append(content, (indent + 1).Fill(fmt.Sprintf("Salt - %s", values.DumpByte(s.buf[2:10]))))
		c := uint32(s.buf[10])
		count := (uint32(16) + (c & 15)) << ((c >> 4) + EXPBIAS)
		content = append(content, (indent + 1).Fill(fmt.Sprintf("Count - %d (coded count 0x%02x)", count, c)))
		s.left -= 10
	case 101:
		mrk := string(s.buf[1:5])
		switch mrk {
		case "GNU1":
			content = append(content, (indent + 1).Fill("GnuPG gnu-dummy (s2k 1001)"))
			s.left -= 4
		case "GNU2":
			content = append(content, (indent + 1).Fill("GnuPG gnu-divert-to-card (s2k 1001)"))
			l := s.buf[5]
			content = append(content, (indent + 2).Fill(fmt.Sprintf("Serial Number: %s", values.DumpByte(s.buf[6:6+1]))))
			s.left -= 5 + int(l)
		default:
			s.left -= 4
		}
	}
	return content
}
<|endoftext|>