Skip to content

Commit

Permalink
Merge pull request arduino#50 from bcmi-labs/core-implementation
Browse files Browse the repository at this point in the history
Core implementation
  • Loading branch information
saniales authored Aug 28, 2017
2 parents c388a83 + 5e7c861 commit 2161657
Show file tree
Hide file tree
Showing 48 changed files with 2,803 additions and 582 deletions.
8 changes: 5 additions & 3 deletions .drone.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ pipeline:
build:
image: golang:latest
commands:
- go get
- go test
- go build
- go get "github.com/stretchr/testify/assert"
- go get ./...
- go build -o arduino
- go test ./... -race
secrets: [TEST_USERNAME, TEST_PASSWORD]
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@ debug
arduino
arduino-cli
main
.vscode/settings.json
.vscode/settings.json
cmd/formatter/debug.test
10 changes: 10 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,15 @@
"args": ["core", "list", "--format", "json"],
"showLog": true
},
{
"name": "Launch CORE DOWNLOAD",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceRoot}/main.go",
"env": {},
"args": ["core", "download", "arduino:samd"],
"showLog": true
},
]
}
26 changes: 22 additions & 4 deletions README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,25 @@ Use "arduino [command] --help" for more information about a command.

To contribute to this project:

. `git clone` this repository.
. Create a new branch with the name `feature-to-implement` or `bug-to-fix`.
. Code your contribution and push to your branch.
. Make a PR (Pull Request).
. `git clone` this repository
. Create a new branch with the name `feature-to-implement` or `bug-to-fix`
. Code your contribution and push to your branch
. Ask a Pull Request

== Tips and Tricks
==== Download all libraries of the current library index:
[source, bash]
----
$ arduino lib search | tr "\n" " " | xargs arduino lib install
----
Same trick can be used on cores as well:
[source, bash]
----
$ arduino core search | tr "\n" " " | xargs arduino core install
----
And with the `download` command:
[source, bash]
----
$ arduino lib search | tr "\n" " " | xargs arduino lib download
$ arduino core search | tr "\n" " " | xargs arduino core download
----
10 changes: 9 additions & 1 deletion auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -272,7 +272,7 @@ func (c *Config) requestToken(client *http.Client, code string) (*Token, error)
}

req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.SetBasicAuth("cli", "")
req.SetBasicAuth(c.ClientID, "")
res, err := client.Do(req)
if err != nil {
return nil, err
Expand All @@ -283,6 +283,14 @@ func (c *Config) requestToken(client *http.Client, code string) (*Token, error)
return nil, err
}

if res.StatusCode != 200 {
data := struct {
Error string `json:"error_description"`
}{}
json.Unmarshal(body, &data)
return nil, errors.New(data.Error)
}

data := Token{}

err = json.Unmarshal(body, &data)
Expand Down
64 changes: 64 additions & 0 deletions auth/auth_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
package auth_test

import (
"encoding/json"
"flag"
"io/ioutil"
"net/http"
"os"
"testing"

"github.com/bcmi-labs/arduino-cli/auth"
)

var (
testUser = os.Getenv("TEST_USERNAME")
testPass = os.Getenv("TEST_PASSWORD")
)

func TestMain(m *testing.M) {
flag.Parse()
os.Exit(m.Run())
}

func TestToken(t *testing.T) {
if testUser == "" || testPass == "" {
t.Skip("Skipped because user and pass were not provided")
}
auth := auth.New()
token, err := auth.Token(testUser, testPass)
if err != nil {
t.Fatal(err)
}

// Obtain info
req, err := http.NewRequest("GET", "https://auth.arduino.cc/v1/users/byID/me", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Add("Authorization", "Bearer "+token.Access)
client := http.Client{}
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}

if resp.StatusCode != 200 {
t.Fatal(resp.StatusCode)
}

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

var data struct{ Username string }
err = json.Unmarshal(body, &data)
if err != nil {
t.Fatal(err)
}

if data.Username != testUser {
t.Fatalf("Expected username '%s', got '%s'", testUser, data.Username)
}
}
124 changes: 79 additions & 45 deletions cmd/arduino.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ package cmd
import (
"fmt"
"os"
"os/user"

"github.com/bcmi-labs/arduino-cli/cmd/formatter"
"github.com/bcmi-labs/arduino-cli/cmd/output"
homedir "github.com/mitchellh/go-homedir"
"github.com/bcmi-labs/arduino-cli/common"
"github.com/bcmi-labs/arduino-cli/configs"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

const (
Expand Down Expand Up @@ -71,33 +72,87 @@ const (

var versions = make(map[string]string)

// arduinoCmd represents the base command when called without any subcommands
var arduinoCmd = &cobra.Command{
// ArduinoCmd represents the base command when called without any subcommands
var ArduinoCmd = &cobra.Command{
Use: "arduino",
Short: "Arduino CLI",
Long: "Arduino Create Command Line Interface (arduino-cli)",
BashCompletionFunction: bashAutoCompletionFunction,
PersistentPreRun: arduinoPreRun,
RunE: arduinoRun,
Example: `arduino --generate-docs to generate the docs and autocompletion for the whole CLI.
arduino --home /new/arduino/home/folder`,
}

// arduinoVersionCmd represents the version command.
var arduinoVersionCmd = &cobra.Command{
Use: "version",
Short: "Shows version Number of arduino",
Long: `Shows version Number of arduino which is installed on your system.`,
Short: "Shows version Number of arduino CLI components",
Long: `Shows version Number of arduino CLI components which are installed on your system.`,
Run: executeVersionCommand,
Example: `arduino version # for the versions of all components.
arduino lib version # for the version of the lib component.
arduino core version # for the version of the core component.`,
}

func init() {
cobra.OnInitialize(initConfig)

versions[arduinoCmd.Name()] = ArduinoVersion
arduinoCmd.PersistentFlags().CountVarP(&GlobalFlags.Verbose, "verbose", "v", "enables verbose output (use more times for a higher level)")
arduinoCmd.PersistentFlags().StringVar(&GlobalFlags.Format, "format", "invalid", "the output format, can be [text|json]")
arduinoCmd.Flags().StringVar(&rootCmdFlags.ConfigFile, "config", "", "config file (default is $HOME/.arduino.yaml)")
arduinoCmd.Flags().BoolVar(&rootCmdFlags.GenerateDocs, "generate-docs", false, "generates the docs for the CLI and puts it in docs folder")
arduinoCmd.AddCommand(arduinoVersionCmd)
versions[ArduinoCmd.Name()] = ArduinoVersion
InitFlags()
InitCommands()
}

// InitFlags reinitialize flags (useful for testing too)
func InitFlags() {
ArduinoCmd.ResetFlags()
arduinoVersionCmd.ResetFlags()

arduinoLibCmd.ResetFlags()
arduinoLibInstallCmd.ResetFlags()
arduinoLibDownloadCmd.ResetFlags()
arduinoLibListCmd.ResetFlags()
arduinoLibSearchCmd.ResetFlags()
arduinoLibUninstallCmd.ResetFlags()
arduinoLibVersionCmd.ResetFlags()

arduinoCoreCmd.ResetFlags()
arduinoCoreDownloadCmd.ResetFlags()
arduinoCoreInstallCmd.ResetFlags()
arduinoCoreListCmd.ResetFlags()
arduinoCoreVersionCmd.ResetFlags()

arduinoConfigCmd.ResetFlags()
arduinoConfigInitCmd.ResetFlags()

ArduinoCmd.PersistentFlags().CountVarP(&GlobalFlags.Verbose, "verbose", "v", "enables verbose output (use more times for a higher level)")
ArduinoCmd.PersistentFlags().StringVar(&GlobalFlags.Format, "format", "invalid", "the output format, can be [text|json]")
ArduinoCmd.PersistentFlags().StringVar(&GlobalFlags.Home, "home", "", "the custom home (if not specified $HOME will be used)")

ArduinoCmd.Flags().BoolVar(&rootCmdFlags.GenerateDocs, "generate-docs", false, "generates the docs for the CLI and puts it in docs folder")

arduinoLibCmd.Flags().BoolVar(&arduinoLibFlags.updateIndex, "update-index", false, "Updates the libraries index")

arduinoCoreCmd.Flags().BoolVar(&arduinoCoreFlags.updateIndex, "update-index", false, "Updates the index of cores to the latest version")

arduinoConfigInitCmd.Flags().BoolVar(&arduinoConfigInitFlags.Default, "default", false, "If omitted, ask questions to the user about setting configuration properties, otherwise use default configuration")
arduinoConfigInitCmd.Flags().StringVar(&arduinoConfigInitFlags.Location, "location", configs.DefaultLocation)
}

// InitCommands reinitialize commands (useful for testing too)
func InitCommands() {
ArduinoCmd.ResetCommands()
arduinoLibCmd.ResetCommands()
arduinoCoreCmd.ResetCommands()
arduinoConfigCmd.ResetCommands()

ArduinoCmd.AddCommand(arduinoVersionCmd, arduinoLibCmd, arduinoCoreCmd, arduinoConfigCmd)

arduinoLibCmd.AddCommand(arduinoLibInstallCmd, arduinoLibUninstallCmd, arduinoLibSearchCmd,
arduinoLibVersionCmd, arduinoLibListCmd, arduinoLibDownloadCmd)

arduinoCoreCmd.AddCommand(arduinoCoreListCmd, arduinoCoreDownloadCmd, arduinoCoreVersionCmd,
arduinoCoreInstallCmd)

arduinoConfigCmd.AddCommand(arduinoConfigInitCmd)
}

func arduinoPreRun(cmd *cobra.Command, args []string) {
Expand All @@ -110,6 +165,15 @@ func arduinoPreRun(cmd *cobra.Command, args []string) {
formatter.PrintErrorMessage("Invalid Call : should show Help, but it is available only in TEXT mode")
})
}
if GlobalFlags.Home == "" {
usr, err := user.Current()
if err != nil {
common.RootDirPath = GlobalFlags.Home
}
common.RootDirPath = usr.HomeDir
} else {
common.RootDirPath = GlobalFlags.Home
}
}

func arduinoRun(cmd *cobra.Command, args []string) error {
Expand All @@ -133,42 +197,12 @@ func arduinoRun(cmd *cobra.Command, args []string) error {

// Execute adds all child commands to the root command sets flags appropriately.
func Execute() {
err := arduinoCmd.Execute()
err := ArduinoCmd.Execute()
if err != nil {
os.Exit(1)
}
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
if rootCmdFlags.ConfigFile != "" {
// Use config file from the flag.
viper.SetConfigFile(rootCmdFlags.ConfigFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
base := "Error while searching for home directory for this user"
if GlobalFlags.Verbose > 0 {
base += fmt.Sprintf(": %s\n", err)
}
formatter.PrintErrorMessage(base)
os.Exit(1)
}

// Search config in home directory with name ".arduino-cli" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".arduino")
}

//viper.AutomaticEnv() // Reads in environment variables that match

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
formatter.Print(fmt.Sprintln("Using config file:", viper.ConfigFileUsed()))
}
}

func executeVersionCommand(cmd *cobra.Command, args []string) {
versionPrint(versionsToPrint(cmd, true)...)
}
Expand Down
Loading

0 comments on commit 2161657

Please sign in to comment.